0

I am using Json.Net to deserialize

I have a c# class that has a property of this type of enum:

public enum MyEnum {
  House,   
  Cat,
  Dog
 }

The Json I have:

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

House and Cat deserializes, but Dog<woof> of course doesn't. How can I get Json.Net to ignore or handle the woof ?

Ian Vink
  • 66,960
  • 104
  • 341
  • 555
  • Perhaps a custom JsonConverter for this type/enum? (not sure though if JsonConverter can be used for customizing enum serialization, never did that myself...) –  Sep 26 '18 at 21:46
  • What happens now (e.g. exception is thrown)? What do you want to happen instead? – mjwills Sep 26 '18 at 21:48
  • 3
    Why keep the `` part in the first place? An enum is the wrong type to use here if your values are not themselves valid enumerations. – Jeff Mercado Sep 26 '18 at 21:50
  • That's not valid json, you appear to have duplicate keys. – Ben Sep 26 '18 at 21:59
  • Looks like a duplicate of [How can I ignore unknown enum values during json deserialization?](https://stackoverflow.com/q/22752075/3744182). Agree? – dbc Sep 26 '18 at 21:59
  • Or if you want to actually strip off the `` and deserialize to `Dog`, see maybe [Json.net Custom enum converter](https://stackoverflow.com/a/32057245/3744182). – dbc Sep 26 '18 at 22:06

1 Answers1

3

You will need to define a custom JsonConverter. This might look something like this:

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

Then decorate your enum with a [JsonConverter] attribute:

[JsonConverter(typeof(MyEnumConverter))]
enum MyEnum
{
  House,
  Dog,
  Cat,
}
Eric Damtoft
  • 1,353
  • 7
  • 13