JSON如何在反序列化期间忽略缺少的对象

时间:2015-06-19 02:20:25

标签: c# json

我有一个示例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中缺少年龄,我该如何忽略它?

1 个答案:

答案 0 :(得分:2)

<强>更新 当你说你使用json.net时

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

import Foundation

func +<T: IntegerType>(lhs: String.Index, rhs: T) -> String.Index {
    var r = lhs
    var x = rhs
    while x > 0 { // advance() won't work because IntegerType and String.Index are incompatible 
        r = r.successor()
        x--
    }
    while x < 0 {
        r = r.predecessor()
        x++
    }
    return r
}

func -<T: IntegerType>(lhs: String.Index, rhs: T) -> String.Index {
    var r = lhs
    var x = rhs
    while x > 0 {
        r = r.predecessor()
        x--
    }
    while x < 0 {
        r = r.successor()
        x++
    }
    return r
}

extension NSRange {
    init(range: Range<Int>) {
        location = range.startIndex
        length = range.endIndex - range.startIndex
    }

    var range: Range<Int> { return Range<Int>(start: location, end: location + length) }
}

extension String {
    var nsrange: NSRange { return NSMakeRange(0, count(self)) }

    var range: Range<Int> { return Range<Int>(start: 0, end: count(self)) }

    subscript (index: Int) -> String {
        return self[index...index]
    }

    subscript (index: Int) -> Character {
        return self[index] as Character
    }

    subscript (range: Range<String.Index>) -> String {
        return substringWithRange(range)
    }

    subscript (range: NSRange) -> String {
        return self[toStringRange(range)]
    }

    // allows "abcd"[0...1] // "ab"
    subscript (range: Range<Int>) -> String {
        return self[toStringRange(range)]
    }

    func toStringRange(range: NSRange) -> Range<String.Index> {
        return toStringRange(range.range)
    }

    func toStringRange(range: Range<Int>) -> Range<String.Index> {
        let start = startIndex + max(range.startIndex, 0)
        let end = startIndex + min(range.endIndex, count(self))
        return Range<String.Index>(start: start, end: end)
    }
}

如果是真正的POCO对象,我检查是否有任何属性为null,我分配了空白对象。 像

JsonSerializerSettings.NullValueHandling = NullValueHandling.Ignore

然后反序列化它。