Convert from json to Enum with Newtonsoft C#

后端 未结 2 2059
粉色の甜心
粉色の甜心 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:20

    Here is my version of an enum converter for ANY enum type... it will handle either a numeric value or a string value for the incoming value. As well as nullable vs non-nullable results.

    public class MyEnumConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            if (!objectType.IsEnum)
            {
                var underlyingType = Nullable.GetUnderlyingType(objectType);
                if (underlyingType != null && underlyingType.IsEnum)
                    objectType = underlyingType;
            }
    
            return objectType.IsEnum;
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (!objectType.IsEnum)
            {
                var underlyingType = Nullable.GetUnderlyingType(objectType);
                if (underlyingType != null && underlyingType.IsEnum)
                    objectType = underlyingType;
            }
    
            var value = reader.Value;
    
            string strValue;
            if (value == null || string.IsNullOrWhiteSpace(value.ToString()))
            {
                if (existingValue == null || Nullable.GetUnderlyingType(existingValue.GetType()) != null)
                    return null;
                strValue = "0";
            }
            else 
                strValue = value.ToString();
    
            int intValue;
            if (int.TryParse(strValue, out intValue))
                return Enum.ToObject(objectType, intValue);
    
            return Enum.Parse(objectType, strValue);
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
    
    0 讨论(0)
  • 2020-12-11 21:23

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题