Convert from json to Enum with Newtonsoft C#

后端 未结 2 2070
粉色の甜心
粉色の甜心 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();
        }
    }
    

提交回复
热议问题