我有一个示例 JSON,当我反序列化时,我得到“对象引用未设置为对象的实例”,因为我发现有时该字段丢失,然后它会再次出现。
json 与此类似
{
"title": "Example",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
}
}
}
如果我反序列化它并将其映射到相应的字段,结果就可以了
但是如果例如“年龄”缺失
{
"title": "Example",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
},
"required": ["firstName", "lastName"]
}
它将抛出错误“对象引用未设置到对象的实例” 如果 JSON 中缺少年龄,我该如何忽略它?
最佳答案
更新 当你说你使用 json.net
我会说 Json.net 有设置,请尝试以下操作
JsonSerializerSettings.NullValueHandling = NullValueHandling.Ignore
如果它是真实的 POCO 对象,我检查是否有任何属性为 null,然后我分配给空白对象。 喜欢
if(MyObject.Properties.Age==null)
{
MyObject.Properties.Age = new Age();
}
然后反序列化它。
关于c# - JSON如何在反序列化过程中忽略丢失的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30928903/