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 ?

6
  • Perhaps a custom JsonConverter for this type/enum? (not sure though if JsonConverter can be used for customizing enum serialization, never did that myself...) Commented Sep 26, 2018 at 21:46
  • What happens now (e.g. exception is thrown)? What do you want to happen instead? Commented Sep 26, 2018 at 21:48
  • 3
    Why keep the <woof> part in the first place? An enum is the wrong type to use here if your values are not themselves valid enumerations. Commented Sep 26, 2018 at 21:50
  • That's not valid json, you appear to have duplicate keys. Commented Sep 26, 2018 at 21:59
  • Looks like a duplicate of How can I ignore unknown enum values during json deserialization?. Agree? Commented Sep 26, 2018 at 21:59

1 Answer 1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.