21

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.

3
  • 1
    How are you doing the JSON serialization? Depending on which serializer you use, it may or may not have an option of serializing enum values as strings. Commented May 19, 2012 at 14:51
  • I am using default serializer that ships with asp.net web api beta Commented May 20, 2012 at 19:28
  • 1
    possible duplicate of JSON serialization of c# enum as string Commented May 20, 2012 at 23:41

3 Answers 3

36

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Needs a single ; at the end of line 1
1

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

Comments

0

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
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.