简体   繁体   English

JSON 如何在反序列化过程中忽略丢失的对象

[英]JSON how to ignore missing object during deserialization

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,当我反序列化时,我得到“对象引用未设置为对象的实例”,因为我发现有时该字段丢失然后它会再次出现。

the json is similar to this 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"]
}

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 中丢失,我如何忽略年龄?


Update when you said you using json.net当你说你使用 json.net 时更新

I will say there is setting for Json.net try the below我会说 Json.net 有设置试试下面

JsonSerializerSettings.NullValueHandling = NullValueHandling.Ignore

if its real POCO object, I check if any property there with null, I assigned then with blank object.如果它是真正的 POCO 对象,我检查那里是否有任何属性为 null,然后我分配了空白对象。 like喜欢

if(MyObject.Properties.Age==null)
{
   MyObject.Properties.Age = new Age();
}

then deserialize it.然后反序列化它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM