Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JsonConverterAttribute with array/list [duplicate]

You can serialize an enum field in an WebAPI model as a string by adding an attribute:

enum Size
{
    Small,
    Medium,
    Large
}

class Example1
{
    [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
    Size Size { get; set; }
}

This will serialize to this JSON:

{
  "Size": "Medium"
}

How can I accomplish the same for a collections of enums?

class Example2
{
    IList<Size> Sizes { get; set; }
}

I want to serialize to this JSON:

{
  "Sizes":
  [
    "Medium",
    "Large"
  ]
}
like image 231
Jon-Eric Avatar asked Sep 09 '26 17:09

Jon-Eric


2 Answers

You need to use JsonPropertyAttribute.ItemConverterType property:

class Example2
{
    [JsonProperty (ItemConverterType = typeof(StringEnumConverter))]
    public IList<Size> Sizes { get; set; }
}
like image 133
Athari Avatar answered Sep 12 '26 06:09

Athari


I have this in the startup code of my web app to serialise all enums to strings (I prefer passing enum names to values, makes things more robust).

Must admit I've never tried it on a list of enums though so I don't know what it would do with that - might be worth a try.

var jsonFormatter = config.Formatters.JsonFormatter;
jsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter { CamelCaseText = true });
like image 33
MarcE Avatar answered Sep 12 '26 08:09

MarcE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!