Convert from json to Enum with Newtonsoft C#

后端 未结 2 2065
粉色の甜心
粉色の甜心 2020-12-11 20:54

How could i deserialize json into a List of enum in C#?

I wrote the following code:

  //json \"types\" : [ \"hotel\", \"spa\" ]

   public enum eTy         


        
2条回答
  •  心在旅途
    2020-12-11 21:23

    A custom converter may help.

    var hType = JsonConvert.DeserializeObject(
                                @"{""types"" : [ ""hotel"", ""spa"" ]}",
                                new MyEnumConverter());
    

    public class HType
    {
        public List 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();
        }
    }
    

提交回复
热议问题