如何将枚举数组序列化为字符串的Json数组

如何将枚举数组序列化为字符串的Json数组

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

问题描述

基于迭戈在此问题中投票最高的答案下未得到回答的评论:

Based on Diego's unanswered comment under the top-voted answer in this question:

以字符串形式将枚举的JSON序列化

对于一个枚举:

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

例如属性:

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

对于类似JSON的内容:

To something like the JSON:

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

代替

{ContactTypes : [0,1,2]}

与普通的JavaScriptSerializer一样吗?

As is the case with the normal JavaScriptSerializer?

推荐答案

似乎在Json.NET的更高版本之一中,通过 ItemConverterType 属性/html/T_Newtonsoft_Json_JsonPropertyAttribute.htm"rel =" nofollow noreferrer> JsonProperty 属性,如此处所述:

It would appear that in one of the later versions of Json.NET there is proper provision for this, via the ItemConverterType property of the JsonProperty attribute, as documented here:

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

当我遇到从Json.NET 3.5升级与我自己的项目相关的问题时,我无法尝试.最后,根据Shmiddty的建议,我将视图模型转换为IEnumerable<string>(尽管仍然存在阻抗不匹配,以后我会重新重构它).

I was unable to try it out as I hit problems upgrading from Json.NET 3.5 that were related to my own project. In the end I converted my viewmodel to IEnumerable<string> as per Shmiddty's suggestion (there is still an impedance mismatch though and I will come back to refactor this in future).

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

Hope that helps anyone else with the same problem!

示例用法:

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

这篇关于如何将枚举数组序列化为字符串的Json数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 14:34