1

I have a json string like so

{
  'EnumValue': 'Foo'
}

I'm deserializing this value to a class with an enum which has the possible values Bar and Baz.
Since "Foo" is not included in this enum, converting this string to a class instance with Newtonsofts JsonConverter throws an error.
Is there any way I can include a default value in my enum that catches all arbitrary values?
The code can be found in this fiddle.

3x071c
  • 955
  • 10
  • 40
  • I think this answer will help you out https://stackoverflow.com/questions/31651523/c-sharp-enum-deserialization-with-json-net-error-converting-value-to-type – ejwill Apr 24 '20 at 14:17
  • @ejwill Yes, that was what I was looking for. Thank you! – 3x071c Apr 24 '20 at 14:42

1 Answers1

1

From what I understand from how Newtonsoft parses enums, it is not possible.

You can try to add a string property and parse it in a get property (Fiddle here) :

public SampleEnum EnumRealValue {
    get {
        if(Enum.TryParse<SampleEnum>(EnumValue, out SampleEnum result)) {
            return result;
        } else {
            return default(SampleEnum);
        }
    }
}
public string EnumValue {get; set;}
Vincent
  • 304
  • 2
  • 5