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

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

问题描述

我有一个包含一个枚举属性的类,并且在使用的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屋!

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