JavaScriptSerializer - JSON serialization of enum as string

后端 未结 27 1707
耶瑟儿~
耶瑟儿~ 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 03:58

    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 {
                new Newtonsoft.Json.Converters.StringEnumConverter()
            }
        })
    

提交回复
热议问题