【问题标题】:JSON how to ignore missing object during deserializationJSON如何在反序列化期间忽略丢失的对象
【发布时间】: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});在反序列化结束时它仍然会引发错误。

标签: c# json


【解决方案1】:

更新 当你说你使用 json.net 时

我会说有 Json.net 的设置试试下面

JsonSerializerSettings.NullValueHandling = NullValueHandling.Ignore

如果它是真正的 POCO 对象,我检查那里是否有任何属性为 null,然后我用空白对象分配。 喜欢

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

然后反序列化它。

【讨论】:

  • 我要在课堂上添加这个吗?
  • [JsonProperty("age", NullValueHandling = NullValueHandling.Ignore)]
  • 是的...您可以添加任何一种方式..我的意思是添加作为“AGE”属性的属性或其他任何属性..或者您可以使用 JsonSerializerSetting 静态类为所有人设置中心化。
猜你喜欢
  • 2014-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-17
  • 2014-01-13
  • 2017-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多