What exceptions does Newtonsoft.Json.DeserializeObject throw?

强颜欢笑 提交于 2021-02-05 12:52:10

问题


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


回答1:


JSON.NET defines the following exceptions:

  • JsonException
    • JsonReaderException
    • JsonSerializationException
    • JsonWriterException
    • JsonSchemaException

Serialization or deserialization errors will typically result in a JsonSerializationException.




回答2:


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.



回答3:


Its JsonReaderException.

Check below1

And it can be handled easily 2



来源:https://stackoverflow.com/questions/26264547/what-exceptions-does-newtonsoft-json-deserializeobject-throw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!