JavaScriptSerializer - 将枚举作为字符串的 JSON 序列化 [英] JavaScriptSerializer - JSON serialization of enum as string

查看:38
本文介绍了JavaScriptSerializer - 将枚举作为字符串的 JSON 序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 enum 属性的类,在使用 JavaScriptSerializer 序列化对象时,我的 json 结果包含枚举的整数值而不是它的 string 名称".有没有办法在我的 json 中将枚举作为 string 获取而无需创建自定义 JavaScriptConverter?也许我可以用一个属性来装饰 enum 定义或对象属性?

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?

举个例子:

enum Gender { Male, Female }

class Person
{
    int Age { get; set; }
    Gender Gender { get; set; }
}

所需的 JSON 结果:

Desired JSON result:

{ "Age": 35, "Gender": "Male" }

理想情况下寻找内置 .NET 框架类的答案,如果不可能,欢迎使用替代方案(如 Json.net).

Ideally looking for answer with built-in .NET framework classes, if not possible alternatives (like Json.net) are welcome.

推荐答案

没有可以使用的特殊属性.JavaScriptSerializerenums 序列化为它们的数值而不是它们的字符串表示.您需要使用自定义序列化将 enum 序列化为其名称而不是数值.

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.

如果您可以使用 JSON.Net 而不是 JavaScriptSerializer,请参阅此问题的答案OmerBakhari 提供:JSON.net 涵盖了这个用例(通过属性 [JsonConverter(typeof(StringEnumConverter)))]) 以及许多其他内置 .net 序列化程序未处理的内容.这里是比较序列化程序特性和功能的链接.

If you can use JSON.Net instead of JavaScriptSerializer than see answer on this question provided 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.

这篇关于JavaScriptSerializer - 将枚举作为字符串的 JSON 序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆