JSON serialization of enum as string
I have a class that contains an enum
property, and upon serializing the object using JavaScriptSerializer
, my json result contains the integer value of the enumeration rather than its string
"name". Is there a way to get the enum as a string
in my json without having to create a custom JavaScriptConverter
? Perhaps there's an attribute that I could decorate the enum
definition, or object property, with?
As an example:
enum Gender { Male, Female }
class Person
{
int Age { get; set; }
Gender Gender { get; set; }
}
Desired json result:
{ "Age": 35, "Gender": "Male" }
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.
Edit: As pointed out 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.
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.
将以下代码添加到您的global.asax中,作为字符串的C#枚举的JSON序列化
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.Formatting =
Newtonsoft.Json.Formatting.Indented;
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add
(new Newtonsoft.Json.Converters.StringEnumConverter());
链接地址: http://www.djcxy.com/p/8400.html
上一篇: 在OAuth 2中访问令牌撤销实施
下一篇: JSON序列化为字符串的枚举