JSON如何在反序列化期间忽略丢失的对象 [英] JSON how to ignore missing object during deserialization
问题描述
我有一个示例JSON,当我反序列化时得到对象引用未设置为对象实例",因为我发现某些字段有时会丢失,然后它将再次出现.
I have a sample JSON that when i deserialize i get "object reference not set to instance of an object" because i found out some that sometimes the field is missing then it will reappear again.
json与此类似
{
"title": "Example",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
}
}
}
如果我反序列化并将其映射到相应的字段,结果就可以了
if i deserialize this and map it to the corresponding fields the result is OK
但是例如,如果缺少年龄"
but if for example the "Age" is missing
{
"title": "Example",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
},
"required": ["firstName", "lastName"]
}
它将引发错误对象引用未设置为对象实例" 如果JSON中缺少年龄,我该如何忽略?
it will throw an error "object reference not set to instance of an object" how do i ignore the age if it's missing in JSON?
推荐答案
更新 当你说你使用json.net
Update when you said you using json.net
我会说Json.net已有设置,请尝试以下
I will say there is setting for Json.net try the below
JsonSerializerSettings.NullValueHandling = NullValueHandling.Ignore
如果它是真正的POCO对象,则检查那里是否有任何带null的属性,然后再分配一个空白对象. 喜欢
if its real POCO object, I check if any property there with null, I assigned then with blank object. like
if(MyObject.Properties.Age==null)
{
MyObject.Properties.Age = new Age();
}
然后反序列化它.
这篇关于JSON如何在反序列化期间忽略丢失的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!