javascript - 如何将枚举数组序列化为 Json 字符串数组?

标签 javascript json.net javascriptserializer

<分区>

基于 Diego 在这个问题中投票最多的答案下未回答的评论:

JSON serialization of enum as string

所以对于一个枚举:

public enum ContactType
{
    Phone = 0,
    Email = 1,
    Mobile = 2
}

例如。一个属性:

//could contain ContactType.Phone, ContactType.Email, ContactType.Mobile
IEnumerable<ContactType> AvailableContactTypes {get;set;} 

像 JSON 这样的东西:

{ContactTypes : ['Phone','Email','Mobile']}

代替

{ContactTypes : [0,1,2]}

与普通的 JavaScriptSerializer 一样吗?

最佳答案

似乎在 Json.NET 的一个较新版本中,通过 ItemConverterType 对此有适当的规定。 JsonProperty 的属性(property)属性,如此处记录:

http://james.newtonking.com/archive/2012/05/08/json-net-4-5-release-5-jsonproperty-enhancements.aspx

我无法尝试它,因为我遇到了与我自己的项目相关的从 Json.NET 3.5 升级的问题。最后我将我的 View 模型转换为 IEnumerable<string>根据 Shmiddty 的建议(虽然仍然存在阻抗不匹配,我会在未来回来重构它)。

希望对遇到同样问题的其他人有所帮助!

示例用法:

[JsonProperty(ItemConverterType = typeof(StringEnumConverter))]
IEnumerable<ContactType> AvailableContactTypes {get;set;} 

关于javascript - 如何将枚举数组序列化为 Json 字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14964196/

相关文章:

javascript - 如何在 Electron 和 Svelte 中启用移动无框 window 的功能?

javascript - 如何在 Javascript 中加载 KendoGrid 的最后一页?

c# - 如果名称为大写,Newtonsoft JsonConvert.SerializeObject 将忽略 JsonProperty

c# - 在 JSON.NET 中反序列化此对象

c# - 使用 JSON.Net CustomCreationConverter

c#反序列化对象错误的JSON列表

javascript - 从 HTMLCollection 中删除项目

javascript - Element.tagName 总是大写吗?

c# - 序列化对象时检测到循环引用 - C#、Json

c# - 将 json 转换为 c# 对象列表