Reputation: 3661
I have a Json file that can contain booleans with a null value. If I try to Deserialize these boolean I get a InvalidCastException because booleans are not nullable.
The line triggering the exception:
var result = serializer.Deserialize(jObject.GetValue(propertyName).CreateReader(), type);
How can I handle this so that I do not get an exception? catch the error and add it to a List, then continue the method. Instead of the application breaking, like it is now.
Upvotes: 1
Views: 2046
Reputation: 392
Create a new JsonSerializerSettings instance..
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
var jsonModel = JsonConvert.DeserializeObject<Customer>(jsonString, settings);
Upvotes: 4
Reputation: 10849
You can define the JsonSerializerSettings
to handle the error. So that program does not throw exception. However in this case, the property will be set to default value if unable to convert/cast.
var settings = new JsonSerializerSettings
{
Error = (sender, args) => { args.ErrorContext.Handled = true; }
};
var jsonModel = JsonConvert.DeserializeObject<Customer>(jsonString, settings);
You can read about this at this Newtonsoft doc link.
Upvotes: 0