Thursday 7 January 2016

Serializing Enums to String in MVC6

Often you will want to change the default serialization of your API responses, to ensure that enums are reflected as strings, not integers. Why? Well, which is more self documenting?

{
  "Status": 1,
  "Message": "things are on fire"
}

or
{
  "Status": "Error",
  "Message": "things are on fire"
}

Fortunately this is really easy in MVC6. The default code uses the ever populate JSON.NET, and it's options are easily exposed. Note that this code example is against RC1, so should actually be correct going forward (the syntax has changed many times across vnext). I'm also assuming you have created your site using the template application, rather than creating an empty ASP.NET application.

Inside the "ConfigureServices" method find

services.AddMvc();

and replace it with

services.AddMvc().AddJsonOptions(options =>
{
    options.SerializerSettings.Converters.Add(new StringEnumConverter());
});

As you can see, you should be able to get at all the other json.net options from here too.

No comments:

Post a Comment