1/27/13

Web API Serialize ENUM Types as String


By default, Web API serializes ENUM data types to the numeric value. For some applications, it would be better to use the string representation instead of the number. An example would be when using  a JavaScript template framework which prevents the need to add implementation code to map the numbers to labels. But before we go crazy and start changing all the model definitions, we should know that there is a way to handle this at the application level.

To address this, we need to add a Media Type Formatter. In Web API, the media type determines how to serialize the data with a built-in support for JSON, XML and form-urlencoded.

The following helper method handles the configuration of the media formatter setting. This code should be added in the global.asax.cs file.

using Newtonsoft.Json;

protected void Application_Start()
{
   SerializeSettings(GlobalConfiguration.Configuration);
                
}


void SerializeSettings(HttpConfiguration config)
{
   JsonSerializerSettings jsonSetting = new JsonSerializerSettings();
   jsonSetting.Converters.Add(new Converters.StringEnumConverter());
   config.Formatters.JsonFormatter.SerializerSettings = jsonSetting;
}

The json serializer setting is configured with a converter which handles the serialization of ENUMs to strings (StringEnumConverter). This setting is then added to the application media formatter collection. This setting is then applied to any of the serialization that takes places during an API call, and the ENUM values should now reflect the string value instead of the number.

We can test this by using a developer's tool like fiddler and look at the JSON raw data that comes back from a WEB API request.