JavaScriptSerializer - JSON serialization of enum as string

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

    This version of Stephen's answer doesn't change the name in the JSON:

    [DataContract(
        Namespace = 
           "http://schemas.datacontract.org/2004/07/Whatever")]
    class Person
    {
        [DataMember]
        int Age { get; set; }
    
        Gender Gender { get; set; }
    
        [DataMember(Name = "Gender")]
        string GenderString
        {
            get { return this.Gender.ToString(); }
            set 
            { 
                Gender g; 
                this.Gender = Enum.TryParse(value, true, out g) ? g : Gender.Male; 
            }
        }
    }
    

提交回复
热议问题