68

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"
  ]
}

2 Answers 2

125

You need to use JsonPropertyAttribute.ItemConverterType property:

class Example2
{
    [JsonProperty (ItemConverterType = typeof(StringEnumConverter))]
    public IList<Size> Sizes { get; set; }
}
Sign up to request clarification or add additional context in comments.

3 Comments

So how to actually populate Sizes?
Thank you so much, been stuck on this for a day and a half
how could I do that with [EnumMember(Value = "?")] EMPTY = '?', so that my model (for [FromBody]) can reflect json with a property that is an array like: [ 'X', '?', 'X' ], yielding: [ MyEnum.X, MyEnum.EMPTY, MyEnum.X ]?
15

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 });

3 Comments

I can confirm this works for a list of enums. My ideal solution would allow opt-in on a per-property basis, but this works and it's better than nothing. Thanks!
@Jon-Eric Athari's solution also works and will give you the per-property opt-in you are looking for.
it doesn't seem to work for Dictionary<int,SomeEnum> though :/

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.