可解码:过滤无法解码的数组

时间:2017-11-28 16:40:45

标签: ios swift swift3.2 decodable

我怎样才能确保我只过滤掉下面的人B,因为人B是唯一的格式错误的对象?

currentIndexUnkeyedDecodingContainer的文档说明:

  

容器的当前解码索引(即索引的索引)   要解码的下一个元素。)每次成功解码后递增   调用

如果您尝试使用try?过滤解码失败,它似乎永远不会进展到数组中的下一个元素。

但是如何实现这一目标呢?请注意,无法更改JSON的结构。

let json = """
{
    "collection" : [
        {
            "name" : "A",
            "surname" : "ob"
        },
        {
            "name" : "B"
        },
        {
            "name" : "C",
            "surname" : "ob"
        },
        {
            "name" : "D",
            "surname" : "ob"
        }
    ]
}
""".data(using: .utf8)!

struct Person: Decodable {
    let name: String
    let surname: String
}

struct Collection: Decodable {
    let items: [Person]

    private enum CodingKeys: String, CodingKey {
        case items = "collection"
    }

    public init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)

        var itemsArr: [Person] = []

        var itemValues = try values.nestedUnkeyedContainer(forKey: .items)
        if let count = itemValues.count {
            for val in (0..<count) {
                print("trying \(val) at index: \(itemValues.currentIndex)")
                if let element = try? itemValues.decode(Person.self) {
                    print("adding \(val)")
                    itemsArr.append(element)
                }
            }
        }

        items = itemsArr
    }
}

let decoder = JSONDecoder()
let collection = try decoder.decode(Collection.self, from: json)
print("collection: \(collection)")

产生输出:

trying 0 at index: 0
adding 0
trying 1 at index: 1
trying 2 at index: 1
trying 3 at index: 1
collection: Collection(items: [__lldb_expr_101.Person(name: "A", surname: "ob")])

0 个答案:

没有答案