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
?
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.
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. ...
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With