JavaScriptSerializer - JSON serialization of enum as string

后端 未结 27 1745
耶瑟儿~
耶瑟儿~ 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:04

    The combination of Omer Bokhari and uri 's answers is alsways my solution since the values that I want to provide is usually different from what I have in my enum specially that I would like to be able to change my enums if I need to.

    So if anyone is interested, it is something like this:

    public enum Gender
    {
       [EnumMember(Value = "male")] 
       Male,
       [EnumMember(Value = "female")] 
       Female
    }
    
    class Person
    {
        int Age { get; set; }
        [JsonConverter(typeof(StringEnumConverter))]
        Gender Gender { get; set; }
    }
    

提交回复
热议问题