.net Newtonsoft.Json.DeserializeObject 抛出哪些异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26264547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 12:49:34  来源:igfitidea点击:

What exceptions does Newtonsoft.Json.DeserializeObject throw?

.netexceptionexception-handlingjson.net

提问by cja

What exceptions does Newtonsoft.Json.DeserializeObject throw? I want to handle them.

Newtonsoft.Json.DeserializeObject 抛出哪些异常?我想处理它们。

http://james.newtonking.com/json/help/?topic=html/M_Newtonsoft_Json_JsonConvert_DeserializeObject.htm#seeAlsoToggle

http://james.newtonking.com/json/help/?topic=html/M_Newtonsoft_Json_JsonConvert_DeserializeObject.htm#seeAlsoToggle

回答by Thomas Levesque

JSON.NET defines the following exceptions:

JSON.NET 定义了以下异常:

  • JsonException
    • JsonReaderException
    • JsonSerializationException
    • JsonWriterException
    • JsonSchemaException
  • JsonException
    • JsonReaderException
    • JsonSerializationException
    • JsonWriterException
    • JsonSchemaException

Serialization or deserialization errors will typically result in a JsonSerializationException.

序列化或反序列化错误通常会导致JsonSerializationException.

回答by Karl Wenzel

Note that Json.NET's error handling documentationshows 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.

请注意,Json.NET 的错误处理文档显示了 API 用户通过处理错误事件而不是直接捕获异常来处理错误的策略。当您考虑到数组中可能只有一项可能无法反序列化时,这是有道理的,并且您可能希望以比整个集合的单一异常更精细的方式处理此问题。

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 Messageproperty, not handle based on the Exceptiontype, 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.Erroris an instance of Exception.

该答案解决了问题的“想要处理它们”部分,而没有涉及“什么例外”部分。正如另一个答案所示,所有 Json.NET 异常都继承自JsonException Class,因此捕获这将是一个很好的故障保护。但是,似乎如果您想真正了解导致抛出异常的原因,则需要阅读其Message属性,而不是根据Exception类型进行处理,因为不同的类型似乎更侧重于您正在执行的操作而不是错误类别。在以下示例代码中,args.ErrorContext.Error是 的实例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.