I have an object with predefined data structure:
public class A
{
public string Id {get;set;}
public bool? Enabled {get;set;}
public int? Age {get;set;}
}
and JSON is supposed to be
{ "Id": "123", "Enabled": true, "Age": 23 }
I want to handle JSON error in positive way, and whenever server returns unexpected values for defined data-types I want it to be ignore and default value is set (null).
Right now when JSON is partially invalid I'm getting JSON reader exception:
{ "Id": "123", "Enabled": "NotABoolValue", "Age": 23 }
And I don't get any object at all. What I want is to get an object:
new A() { Id = "123", Enabled = null, Age = 23 }
and parsing warning if possible. Is it possible to accomplish with JSON.NET?
There is another way. for example, if you are using a nuget package which uses newton json and does deseralization and seralization for you. You may have this problem if the package is not handling errors. then you cant use the solution above. you need to handle in object level. here becomes OnErrorAttribute useful. So below code will catch any error for any property, you can even modify within the OnError function and assign default values
public class PersonError { private List _roles;
}
see https://www.newtonsoft.com/json/help/html/SerializationErrorHandling.htm
Same thing as Ilija's solution, but a oneliner for the lazy/on a rush (credit goes to him)
Props to Jam for making it even shorter =)
To be able to handle deserialization errors, use the following code:
where
HandleDeserializationError
is the following method:The
HandleDeserializationError
will be called as many times as there are errors in the json string. The properties that are causing the error will not be initialized.