在 JSON.NET 数据解析过程中忽略解析错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26107656/
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 17:32:52  来源:igfitidea点击:

Ignore parsing errors during JSON.NET data parsing

jsonerror-handlingjson.netdeserialization

提问by Alexey Strakh

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

和 JSON 应该是

{ "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).

我想以积极的方式处理 JSON 错误,每当服务器为定义的数据类型返回意外值时,我希望它被忽略并设置默认值(空)。

Right now when JSON is partially invalid I'm getting JSON reader exception:

现在当 JSON 部分无效时,我收到 JSON 读取器异常:

{ "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?

并在可能的情况下解析警告。是否可以使用 JSON.NET 来完成?

回答by Ilija Dimov

To be able to handle deserialization errors, use the following code:

为了能够处理反序列化错误,请使用以下代码:

var a = JsonConvert.DeserializeObject<A>("-- JSON STRING --", new JsonSerializerSettings
    {
        Error = HandleDeserializationError
    });

where HandleDeserializationErroris the following method:

HandleDeserializationError以下方法在哪里:

public void HandleDeserializationError(object sender, ErrorEventArgs errorArgs)
{
    var currentError = errorArgs.ErrorContext.Error.Message;
    errorArgs.ErrorContext.Handled = true;
}

The HandleDeserializationErrorwill be called as many times as there are errors in the json string. The properties that are causing the error will not be initialized.

HandleDeserializationError因为有在JSON字符串错误会被称为多次。不会初始化导致错误的属性。

回答by Gaspa79

Same thing as Ilija's solution, but a oneliner for the lazy/on a rush (credit goes to him)

与 Ilija 的解决方案相同,但适合懒惰/匆忙的单线(归功于他)

var settings = new JsonSerializerSettings { Error = (se, ev) => { ev.ErrorContext.Handled = true; } };
JsonConvert.DeserializeObject<YourType>(yourJsonStringVariable, settings);

Props to Jam for making it even shorter =)

Jam 的道具使其更短 =)

回答by batmaci

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 OnErrorAttributeuseful. So below code will catch any error for any property, you can even modify within the OnError function and assign default values

还有另一种方法。例如,如果您使用的是使用 newton json 并为您进行反序列化和序列化的 nuget 包。如果包未处理错误,您可能会遇到此问题。那么你不能使用上面的解决方案。您需要在对象级别处理。这里变得OnErrorAttribute有用。因此,下面的代码将捕获任何属性的任何错误,您甚至可以在 OnError 函数中进行修改并分配默认值

public class PersonError
{
  private List<string> _roles;

  public string Name { get; set; }
  public int Age { get; set; }

  public List<string> Roles
  {
    get
    {
        if (_roles == null)
        {
            throw new Exception("Roles not loaded!");
        }

        return _roles;
    }
    set { _roles = value; }
  }

  public string Title { get; set; }

  [OnError]
  internal void OnError(StreamingContext context, ErrorContext errorContext)
  {
    errorContext.Handled = true;
  }
}

see https://www.newtonsoft.com/json/help/html/SerializationErrorHandling.htm

https://www.newtonsoft.com/json/help/html/SerializationErrorHandling.htm