4

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);
2
  • 1
    What exactly is your problem? Deserializing an HType object would also deserialize its members, including the HTypes list. If it doesn't in your case, post an example JSON file with a serialized HType object, please. Commented Oct 20, 2013 at 18:24
  • It doesn't deserialize to Enum, it doesn't know how to do that. My question is how to deserialize the json from example to enum entries. Commented Oct 20, 2013 at 18:38

2 Answers 2

6

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();
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

While older Json.NET versions suffered from an incomplete (or buggy) StringEnumConverter, this issue has been fixed since roughly a year or so (iirc). Nowadays, you just need to add Json.NET's StringEnumConverter to the serializer settings, and Bob's your uncle...
@elgonzo I knew someone would comment this :) Just try and see that it will not work. If you are sure, post it as answer with working code.
Yes, it does. I use it, including the StringEnumConverter to deserialize enum strings -- this even works with flag-enums. :-) Which Json.NET version are you using? I am using Json.NET 5.0.6.16206 (the DLL for .NET 4.0).
@elgonzo Then post it as answer. (BTW: I just got the latest version of Json.Net from Nuget).
L.B: Holy cow, you got me there :) I totally missed the part regarding the [Description] attribute. You are right. I was the whole time fixated on the enum value names. Now i feel embarrassed... ;)
|
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.