Convert String with Underscores to .Net Enum with Standard Naming Convention

172 views Asked by At

How do I use Json.Net to convert:

{ "key": "an_ugly_value" }

To this:

enum Key
{
  AnUglyValue
}

Pseudo-code to further illustrate problem:

...
class AnObject
{
  public Key Key { get; set; }
}

var anObject = JsonConvert.DeserializeObject<AnObject>("{ \"key\": \"an_ugly_value\" }");

assert(anObject.Key == Key.AnUglyValue);
...   

Thanks to whoever linked to the above answer. Here is some pseudo-code to illustrate the solution:

enum Key
{
  [Description("an_ugly_value")]
  AnUglyValue
}

public class KeyConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Key);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var keyMember = typeof(Key).GetMembers()
                                   .Where(x => x.GetCustomAttributes(typeof(DescriptionAttribute)).Any())
                                   .FirstOrDefault(x => ((DescriptionAttribute)x.GetCustomAttribute(typeof(DescriptionAttribute))).Description == (string)reader.Value);

        return keyMember == null ? Enum.Parse(typeof(Key), (string)reader.Value) : Enum.Parse(typeof(Key), keyMember.Name);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

var anObject = JsonConvert.DeserializeObject<AnObject>("{ \"key\": \"an_ugly_value\" }", new KeyConverter());
0

There are 0 answers