Serialize a container of enums as strings using JSON.net

asp.net-web-api, c#, json.net

Solution

You need to use `JsonPropertyAttribute.ItemConverterType` property:

class Example2
{
    [JsonProperty (ItemConverterType = typeof(StringEnumConverter))]
    public IList<Size> Sizes { get; set; }
}

Problem

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

Original source