0

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.

1 Answer 1

1

Try to add StringEnumConverter into your WebApiConfig

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

          //...........................................
}
Sign up to request clarification or add additional context in comments.

1 Comment

I was about to say that I was doing that already, then I thought I should double check, and behold, I was only using it on the RestSharp client, and not on the API itself. Duh!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.