枚举作为字符串的JSON序列化 [英] JSON serialization of enum as string
问题描述
我有一个包含一个枚举
属性的类,并且在使用的JavaScriptSerializer
序列化对象,我的JSON结果包含枚举,而不是它的字符串
名的整数值。有没有办法让枚举在我的JSON字符串,而无需创建自定义的 JavaScriptConverter
?也许有一个属性,我可以装点枚举定义,或对象属性,用?
作为一个例子:
枚举性别{男,女}类Person
{
INT年龄{搞定;组; }
性别性别{搞定;组; }
}
期望中的JSON结果:
{时代:35,性别:男}
没有出现,你可以使用任何特殊的属性。 的JavaScriptSerializer
连载枚举
来的数值,而不是它们的字符串重新presentation。您需要使用自定义序列化序列化枚举
作为它的名称,而不是数值。
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.
这篇关于枚举作为字符串的JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!