.net - C# Enum deserialization with Json.Net: Error converting value to type -


i'm using json.net serialize/deserialize json apis.

the api response have integer values map enum defined in application.

the enum this:

public enum myenum     {         type1,         type2,         type3 } 

and json api response has following:

{         "name": "abc",         "myenumvalue":"type1" } 

sometimes api returns value myenumvalue field that's not defined in enum, this:

{             "name": "abc",             "myenumvalue":"type4"     } 

that throws exception:

error converting value "type4" type 'myenum'

is there way handle error assigning default value or avoid application crash?

let's have following json string:

[     {         "name": "abc",         "myenumvalue": "type1"     },     {         "name": "abcd",         "myenumvalue": "type2"     },     {         "name": "abcde",         "myenumvalue": "type3"     }    ,     {         "name": "abcdef",         "myenumvalue": "type4"     } ] 

and following class , enum:

public class myclass {     public string name { get; set; }      public myenum myenumvalue { get; set; } }  public enum myenum {     type1,     type2,     type3 } 

as can noticed, json string array contains item (the last one), cannot correctly mapped myenum. avoid deserialization errors can use following code snippet:

static void main(string[] args) {              var serializationsettings = new jsonserializersettings     {         error = handledeserializationerror     };      var lst = jsonconvert.deserializeobject<list<myclass>>(jsonstr, serializationsettings); }  public static void handledeserializationerror(object sender, erroreventargs errorargs) {     errorargs.errorcontext.handled = true;     var currentobj = errorargs.currentobject myclass;      if (currentobj == null) return;     currentobj.myenumvalue = myenum.type2;             } 

where jsonstr variable posted json string above. in above code sample, if myenumvalue cannot correctly interpreted, set default value of type2.

example: https://dotnetfiddle.net/wkd2lt


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -