我有一个预定义数据 struct 的对象:

public class A
{
    public string Id {get;set;}
    public bool? Enabled {get;set;}
    public int? Age {get;set;}
}

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部分无效时,我得到了JSON阅读器异常:

{ "Id": "123", "Enabled": "NotABoolValue", "Age": 23 }

而且我一点也没有得到任何东西.

new A() { Id = "123", Enabled = null, Age = 23 }

并在可能的情况下解析警告. 用JSON.NET可以实现吗?

推荐答案

要处理反序列化错误,请使用以下代码:

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

其中HandleDeserializationError表示以下方法:

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

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

Json相关问答推荐

使用单元和非单元版本反序列化Rust中的枚举,而无需编写自定义反序列化程序

如何在JQ过滤器文件中使用多行?

如何使用PowerShell从ExchangeOnline命令执行中获得JSON输出

使用 jolt 变换压平具有公共列 JSON 的复杂嵌套

报告重复的对象键

在Databricks中如何将JSON文件作为字典读取

使用 jq 将消息转换为数组

JOLT JSON 将值从一对多转换为一对一

使用 jq Select 键:值并输出为数组

PowerShell - 如何迭代 PSCustomObject 嵌套对象?

解析包含换行符的 JSON

如何在golang中获取 struct 的json字段名称?

如何一次加载无限滚动中的所有条目以解析python中的HTML

在 Apache Spark 中读取多行 JSON

jQuery JSON 响应总是触发 ParseError

在自定义 JsonConverter 的 ReadJson 方法中处理空对象

有没有办法折叠 Postman 中的所有 json 字段

杰克逊在通用列表中读取 json

将多个值存储在json中的单个键中

Volley JsonObjectRequest Post 参数不再起作用