Json.Net-在C#中反序列化为枚举

时间:2018-09-26 21:45:40

标签: c# json json.net

我正在使用Json.Net反序列化

我有一个具有此类枚举属性的c#类:

public enum MyEnum {
  House,   
  Cat,
  Dog
 }

我拥有的杰森:

    "MyEnum ": "House",
    "MyEnum ": "Cat",
    "MyEnum ": "Doc<woof>"

HouseCat反序列化,但Dog<woof>当然不是。如何让Json.Net忽略或处理woof

1 个答案:

答案 0 :(得分:2)

您将需要定义一个custom JsonConverter。这可能看起来像这样:

Transaction Id

然后使用[JsonConverter]属性装饰枚举:

class MyEnumConverter : JsonConverter<MyEnum>
{
  public override MyEnum ReadJson(JsonReader reader, Type objectType, MyEnum existingValue, bool hasExistingValue, JsonSerializer serializer)
  {
    var token = reader.Value as string ?? reader.Value.ToString();
    var stripped = Regex.Replace(token, @"<[^>]+>", string.Empty);
    if (Enum.TryParse<MyEnum>(stripped, out var result))
    {
      return result;
    }
    return default(MyEnum);
  }

  public override void WriteJson(JsonWriter writer, MyEnum value, JsonSerializer serializer)
  {
    writer.WriteValue(value.ToString());
  }
}