Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum Serialization Json vs XML

Tags:

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.

like image 964
Muhammad Adeel Zahid Avatar asked May 19 '12 10:05

Muhammad Adeel Zahid


People also ask

Are enums serializable c#?

In C#, JSON serialization very often needs to deal with enum objects. By default, enums are serialized in their integer form. This often causes a lack of interoperability with consumer applications because they need prior knowledge of what those numbers actually mean.

Does JSON support enum?

JSON has no enum type. The two ways of modeling an enum would be: An array, as you have currently. The array values are the elements, and the element identifiers would be represented by the array indexes of the values.

How do you serialize an enum?

To serialize an enum constant, ObjectOutputStream writes the value returned by the enum constant's name method. To deserialize an enum constant, ObjectInputStream reads the constant name from the stream; the deserialized constant is then obtained by calling the java.


1 Answers

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);
like image 119
Jonas Lundgren Avatar answered Oct 25 '22 08:10

Jonas Lundgren