What exceptions does Newtonsoft.Json.DeserializeObject throw?
What exceptions does Newtonsoft.Json.DeserializeObject throw? I want to handle them.
http://james.newtonking.com/json/help/?topic=html/M_Newtonsoft_Json_JsonConvert_DeserializeObject.htm#seeAlsoToggle
JSON.NET defines the following exceptions:
-
JsonException
JsonReaderException
JsonSerializationException
JsonWriterException
JsonSchemaException
Serialization or deserialization errors will typically result in a JsonSerializationException
.
Note that Json.NET's error handling documentation shows a strategy for the API user to deal with errors by handling error events rather than directly catching exceptions. This makes sense when you consider that perhaps only one item in an array may fail to deserialize, and you might want to handle this in a more granular fashion than one monolithic exception for the entire set.
This answer addresses the "want to handle them" part of your question without getting at the "what exceptions" part. As another answer shows, all Json.NET exceptions inherit from JsonException Class, so catching this would be a nice fail-safe. However, it seems that if you want to really understand what caused an exception to be thrown, you would need to read its Message
property, not handle based on the Exception
type, as the different types seem to be more oriented on the action you are performing than the error category. In the following example code, the args.ErrorContext.Error
is an instance of Exception
.
Example code from the documentation:
List<string> errors = new List<string>();
List<DateTime> c = JsonConvert.DeserializeObject<List<DateTime>>(@"[
'2009-09-09T00:00:00Z',
'I am not a date and will error!',
[
1
],
'1977-02-20T00:00:00Z',
null,
'2000-12-01T00:00:00Z'
]",
new JsonSerializerSettings
{
Error = delegate(object sender, ErrorEventArgs args)
{
errors.Add(args.ErrorContext.Error.Message);
args.ErrorContext.Handled = true;
},
Converters = { new IsoDateTimeConverter() }
});
// 2009-09-09T00:00:00Z
// 1977-02-20T00:00:00Z
// 2000-12-01T00:00:00Z
// The string was not recognized as a valid DateTime. There is a unknown word starting at index 0.
// Unexpected token parsing date. Expected String, got StartArray.
// Cannot convert null value to System.DateTime.
Its JsonReaderException.
Check below:
And it can be handled easily