Enum Serialization Json vs XML

2020-04-02 02:11发布

问题:

I have following Enum in my project

public enum CameraAccessMethod
{
    Manual = 0,
    Panasonic = 1,
    Axis = 2,
    AirCam = 3
}

I have an object that is serialized either to json or to XML depending upon different scenarios and one of object's property is of type CameraAccessMethod. The problem i have is that when this property is serialized to XML it will give string representation of enum values (Manual, Panasonic,Axis,Aircam) but in JSON it is serialized to number values (0,1,2,3). How can i avoid this inconsistency? i want strings in JSON serialization as well.

回答1:

Since Web API RC you can get string representations of enums by applying a StringEnumConvert to the existing JsonMediaTypeFormatter converter collection during Application_Start():

var jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
var enumConverter = new Newtonsoft.Json.Converters.StringEnumConverter();
jsonFormatter.SerializerSettings.Converters.Add(enumConverter);


回答2:

You can accomplish this easily if you switch to using a formatter based upon Json.NET (which will ship out of the box with next drop of ASP.NET Web API). See this SO post for details:

How to tell Json.Net globally to apply the StringEnumConverter to all enums



回答3:

To use JsonMediaTypeFormatter and enumConverter both we can use below code. //code start here

var serializerSettings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
var enumConverter = new Newtonsoft.Json.Converters.StringEnumConverter();
serializerSettings.Converters.Add(enumConverter);
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new PartialJsonMediaTypeFormatter()
{
     IgnoreCase = true,
     SerializerSettings = serializerSettings
});