【发布时间】:2015-09-04 21:23:33
【问题描述】:
我有一个示例 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 中缺少年龄,我如何忽略它?
【问题讨论】:
-
你使用什么库?
-
如果它是真正的 POCO 对象,我检查它是否有任何带有 null 的属性,然后我用空白对象分配。喜欢
if(MyObject.Properties.Age==null) { MyObject.Properties.Age = new Age();}然后反序列化它。 -
我使用 json.net 库
-
在您的情况下,“年龄”应该为空。你的lib版本是什么? V6.0.8 的工作原理类似。
-
我尝试添加新的 JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});在反序列化结束时它仍然会引发错误。