从JSON转换为枚举与Newtonsoft C# [英] Convert from json to Enum with Newtonsoft C#
本文介绍了从JSON转换为枚举与Newtonsoft C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎么能反序列化到JSON的枚举在C#中的列表?
我写了下面的代码:
// JSON类型:酒店,温泉]
公共枚举ETYPE
{
[说明(酒店)]
kHotel,
[说明(SPA)]
kSpa
}
公共类HTYPE
{
名单,LT; ETYPE> m_types;
[JsonProperty(类型)]
公开名单<&ETYPE GT; HTypes {
获得
{
返回m_types;
}
组
{
//我这样做是为了尝试和二传手
//应该是什么枚举值每种类型的
决定/ /利用Description属性
的//而是抛出一个异常
}
}
}
//其他类
VAR hTypes = JsonConvert.DeserializeObject< HTYPE>(JSON);
解决方案
自定义的转换的可能。帮助
VAR HTYPE = JsonConvert.DeserializeObject< HTYPE>(
@{类型: ,酒店,,温泉,]},
新MyEnumConverter());
公开类HTYPE
{
公开名单<&ETYPE GT;类型{设置;得到; }
}
公共枚举ETYPE
{
[说明(酒店)]
kHotel,
[说明(温泉 )
kSpa
}
公共类MyEnumConverter:JsonConverter
{
公众覆盖布尔CanConvert(类型的objectType)
{
返回的objectType == typeof运算(ETYPE);
}
公众覆盖对象ReadJson(JsonReader读者,类型的objectType,对象existingValue,JsonSerializer串行)
{
VAR eTypeVal = typeof运算(ETYPE).GetMembers()
。凡(X => x.GetCustomAttributes(typeof运算(DescriptionAttribute))任何()。)
.FirstOrDefault(X =>((DescriptionAttribute)x.GetCustomAttribute(typeof运算(DescriptionAttribute))) .DESCRIPTION ==(串)reader.Value);
如果(eTypeVal == NULL)返回Enum.Parse(typeof运算(ETYPE),(串)reader.Value);
返回Enum.Parse(typeof运算(ETYPE),eTypeVal.Name);
}
公共覆盖无效WriteJson(JsonWriter作家,对象的值,JsonSerializer串行)
{
抛出新NotImplementedException();
}
}
How could i deserialize json into a List of enum in C#?
I wrote the following code:
//json "types" : [ "hotel", "spa" ]
public enum eType
{
[Description("hotel")]
kHotel,
[Description("spa")]
kSpa
}
public class HType
{
List<eType> m_types;
[JsonProperty("types")]
public List<eType> HTypes {
get
{
return m_types;
}
set
{
// i did this to try and decide in the setter
// what enum value should be for each type
// making use of the Description attribute
// but throws an exception
}
} }
//other class
var hTypes = JsonConvert.DeserializeObject<HType>(json);
解决方案
A custom converter may help.
var hType = JsonConvert.DeserializeObject<HType>(
@"{""types"" : [ ""hotel"", ""spa"" ]}",
new MyEnumConverter());
public class HType
{
public List<eType> types { set; get; }
}
public enum eType
{
[Description("hotel")]
kHotel,
[Description("spa")]
kSpa
}
public class MyEnumConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(eType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var eTypeVal = typeof(eType).GetMembers()
.Where(x => x.GetCustomAttributes(typeof(DescriptionAttribute)).Any())
.FirstOrDefault(x => ((DescriptionAttribute)x.GetCustomAttribute(typeof(DescriptionAttribute))).Description == (string)reader.Value);
if (eTypeVal == null) return Enum.Parse(typeof(eType), (string)reader.Value);
return Enum.Parse(typeof(eType), eTypeVal.Name);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
这篇关于从JSON转换为枚举与Newtonsoft C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文