c# - JavaScriptSerializer - JSON serialization of enum as string

ID : 964

viewed : 234

Tags : c#asp.netjsonenumsjavascriptserializerc#

Top 5 Answer for c# - JavaScriptSerializer - JSON serialization of enum as string

vote vote


I have found that Json.NET provides the exact functionality I'm looking for with a StringEnumConverter attribute:

using Newtonsoft.Json; using Newtonsoft.Json.Converters;  [JsonConverter(typeof(StringEnumConverter))] public Gender Gender { get; set; } 

More details at available on StringEnumConverter documentation.

There are other places to configure this converter more globally:

  • enum itself if you want enum always be serialized/deserialized as string:

    [JsonConverter(typeof(StringEnumConverter))]   enum Gender { Male, Female } 
  • In case anyone wants to avoid attribute decoration, you can add the converter to your JsonSerializer (suggested by Bjørn Egil):

    serializer.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());  

    and it will work for every enum it sees during that serialization (suggested by Travis).

  • or JsonConverter (suggested by banana):

    JsonConvert.SerializeObject(MyObject,      new Newtonsoft.Json.Converters.StringEnumConverter()); 

Additionally you can control casing and whether numbers are still accepted by using StringEnumConverter(NamingStrategy, Boolean) constructor.

vote vote


No there is no special attribute you can use. JavaScriptSerializer serializes enums to their numeric values and not their string representation. You would need to use custom serialization to serialize the enum as its name instead of numeric value.

If you can use JSON.Net instead of JavaScriptSerializer than see answer on this question provided by OmerBakhari: JSON.net covers this use case (via the attribute [JsonConverter(typeof(StringEnumConverter))]) and many others not handled by the built in .net serializers. Here is a link comparing features and functionalities of the serializers.

vote vote


Add the below to your global.asax for JSON serialization of c# enum as string

  HttpConfiguration config = GlobalConfiguration.Configuration;             config.Formatters.JsonFormatter.SerializerSettings.Formatting =                 Newtonsoft.Json.Formatting.Indented;              config.Formatters.JsonFormatter.SerializerSettings.Converters.Add                 (new Newtonsoft.Json.Converters.StringEnumConverter()); 
vote vote


@Iggy answer sets JSON serialization of c# enum as string only for ASP.NET (Web API and so).

But to make it work also with ad hoc serialization, add following to your start class (like Global.asax Application_Start)

//convert Enums to Strings (instead of Integer) globally JsonConvert.DefaultSettings = (() => {     var settings = new JsonSerializerSettings();     settings.Converters.Add(new StringEnumConverter { CamelCaseText = true });     return settings; }); 

More information on the Json.NET page

Additionally, to have your enum member to serialize/deserialize to/from specific text, use the


attribute, like this:

public enum time_zone_enum {     [EnumMember(Value = "Europe/London")]      EuropeLondon,      [EnumMember(Value = "US/Alaska")]      USAlaska } 
vote vote


I wasn't able to change the source model like in the top answer (of @ob.), and I didn't want to register it globally like @Iggy. So I combined https://stackoverflow.com/a/2870420/237091 and @Iggy's https://stackoverflow.com/a/18152942/237091 to allow setting up the string enum converter on during the SerializeObject command itself:

Newtonsoft.Json.JsonConvert.SerializeObject(     objectToSerialize,      Newtonsoft.Json.Formatting.None,      new Newtonsoft.Json.JsonSerializerSettings()     {         Converters = new List<Newtonsoft.Json.JsonConverter> {             new Newtonsoft.Json.Converters.StringEnumConverter()         }     }) 

Top 3 video Explaining c# - JavaScriptSerializer - JSON serialization of enum as string