Search code examples
c#serializationenumsjson.netdefault

Deserializing an enum with a default value with Newtonsoft.JSON


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.


Solution

  • 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;}