I'm using Json.NET to serialize/deserialize some JSON APIs.
The API response have some integer values that map to an Enum defined in the application.
The enum is like this:
public enum MyEnum
{
Type1,
Type2,
Type3
}
and the JSON API response has the following:
{
"Name": "abc",
"MyEnumValue":"Type1"
}
sometimes the API returns a value for the MyEnumValue field that's not defined in my enum, like this:
{
"Name": "abc",
"MyEnumValue":"Type4"
}
That throws an exception:
Error converting value "Type4" to type 'MyEnum'
Is there a way to handle this error by assigning a default value or something to avoid the application crash?
DefaultValuefor the property newtonsoft.com/json/help/html/…public class SampleEntity { [JsonProperty("error")] [JsonConverter(typeof(StringEnumConverter))] public ErrorCode Error { get; set; } }or..... if using System.Text.Jsonpublic class SampleEntity { [JsonProperty("error")] [JsonConverter(typeof(JsonStringEnumConverter))] public ErrorCode Error { get; set; } }bytefish.de/blog/enums_json_net.html