JavaScriptSerializer - JSON serialization of enum as string

后端 未结 27 2152
耶瑟儿~
耶瑟儿~ 2020-11-22 03:22

I have a class that contains an enum property, and upon serializing the object using JavaScriptSerializer, my json result contains the integer valu

27条回答
  •  不要未来只要你来
    2020-11-22 04:19

    @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

    System.Runtime.Serialization.EnumMember

    attribute, like this:

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

提交回复
热议问题