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

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

问题描述

我有一个包含 enum 属性的类,并且在使用 JavaScriptSerializer 序列化对象时,我的 json 结果包含枚举的整数值而不是其 字符串名称".有没有办法在我的 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天全站免登陆