Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MediaTypeFormatter serialize enum string values in web api

Consider this code:

public Gender Get()
{
    return Gender.Female;
}
public enum Gender
{
   Male,
   Female
}

This code is a Web API controller that returns Gender enum. When we use XmlTypeFormatter and call the method, it returns Male or Female. But when we use JsonTypeFormatter we get the value of enum, such as 1.

Why is it so?! and how can we get Female or Male from JsonTypeFormatter?

like image 667
Ali RAN Avatar asked Nov 27 '13 12:11

Ali RAN


People also ask

What is mediatypeformatter in web API?

The default format in Web API can be either JSON or XML. A media type formatter that is an object of type MediaTypeFormatter, performs the serialization in the ASP.NET Web API pipeline. To understand this, please have a look at the following action method.

What are the media formats in ASP NET Web API?

Media Formatters in ASP.NET Web API 2 1 Internet Media Types. A media type, also called a MIME type, identifies the format of a piece of data. ... 2 Example: Creating a CSV Media Formatter. The following example shows a media type formatter that can serialize a Product object to a comma-separated values (CSV) format. 3 Character Encodings. ...

Which media type formatters serialize an object into JSON and XML?

The ASP.NET Web API media type formatters that serialize the object into the JSON and XML are JsonMediaTypeFormatter and XmlMediaTypeFormatter respectively. Both the classes are deriving from MediaTypeFormatter class.

How to serialize data in web API framework?

The answer is: By using Media-Type formatters. The Media type formatters are the classes that are responsible for serializing the request/response data so that the Web API Framework can understand the request data format and also send data in the format which the client expects.


1 Answers

In your application start:

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;
}
like image 184
hutchonoid Avatar answered Oct 02 '22 19:10

hutchonoid