问题描述
我有一个包含enum
属性的类,并且在使用JavaScriptSerializer
序列化对象时,我的json结果包含枚举的整数值,而不是其string
"name".有没有一种方法可以在我的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结果:
{ "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.
推荐答案
没有没有可以使用的特殊属性. JavaScriptSerializer
将enums
序列化为其数值,而不是其字符串表示形式.您需要使用自定义序列化来序列化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
,那么请参阅答案 ="https://stackoverflow.com/users/56829/omer-bokhari"> OmerBakhari :JSON.net涵盖了此用例(通过属性[JsonConverter(typeof(StringEnumConverter))]
)以及许多其他内置方法未处理的用例.网络序列化器. 这是一个比较串行器特性和功能的链接.
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序列化为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!