Dan Dinu
Dan Dinu

Reputation: 33378

Convert from json to Enum with Newtonsoft C#

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

Upvotes: 4

Views: 12571

Answers (2)

Brian Rice
Brian Rice

Reputation: 3257

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

Upvotes: 0

L.B
L.B

Reputation: 116108

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

Upvotes: 6

Related Questions