c# - 使用 Newtonsoft C# 从 json 转换为 Enum

标签 c# json json.net

如何在 C# 中将 json 反序列化为枚举列表?

我写了下面的代码:

  //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);

最佳答案

自定义转换器可能会有所帮助。

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();
    }
}

关于c# - 使用 Newtonsoft C# 从 json 转换为 Enum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19481027/

相关文章:

c# - 101 Rx 示例

c# - 从 JSON.net 中的 JArray 获取值

json.net - 发布版本中 PostSharp 中的 AssemblyLoadException

c# - Windows Phone 8 中的 JObject.Parse 动态类型问题

c# - 只允许外部类实例化内部类,但内部类应该是公共(public)的

c# - 如何在 C# 方法中返回 2 个值

c# - 多个 RadioButtonList 并插入到 SQL 中

php - 返回值

python - JSON无法使用 simplejson 序列化python Appengine GeoModel子类

java - 在 java 中将 json 数据从 Ajax 发送到 Servlet?