David Keaveny
David Keaveny

Reputation: 4079

Serialise an array of enums to their string values in JSON.NET

I am working on an API that needs to return an array of enums. I am using JSON.NET with WebAPI, and while the StringEnumConverter is sufficient to convert properties which are enums into their string values, it doesn't convert a result which is just an array of enums, instead it returns just the integer value.

So if my endpoint looks like this:

[RoutePrefix("Items")]
public class ItemsController : ApiController
{
    [HttpGet][Route("")]
    public IHttpActionResult Get()
    {
        var items = Enum.GetValues(typeof(Items))
                        .Cast<Items>()
                        .ToList()
        return Ok(items);
    }
}

public enum Items
{
    First = 0,
    Second = 1,
    Third = 2
}

Then a call to GET /Items currently returns [ 0, 1, 2 ]; what I would like to get back is [ "First", "Second", "Third" ].

What I don't want to have to do is put a wrapper around the result :

public class ItemsList
{
    [JsonProperty("Items", ItemConverterType=typeof(StringEnumConverter))]
    public List<Items> Items { get;set;
}

which, while it might technically work, would result in this endpoint being inconsistent with the rest of the API, which doesn't require wrappers round its results.

Upvotes: 0

Views: 328

Answers (1)

Alexander V.
Alexander V.

Reputation: 1538

Try to add StringEnumConverter into your WebApiConfig

public static void Register(HttpConfiguration config)
{
       config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());

          //...........................................
}

Upvotes: 1

Related Questions