使用标准命名约定将具有下划线的字符串转换为.Net Enum

时间:2015-06-19 19:55:18

标签: c# .net enums json.net json-deserialization

如何使用Json.Net进行转换:

{ "key": "an_ugly_value" }

对此:

enum Key
{
  AnUglyValue
}

伪代码进一步说明问题:

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

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

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

感谢与上述答案相关的任何人。这里有一些伪代码来说明解决方案:

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 个答案:

没有答案