1

由于人 B 是唯一格式错误的对象,如何确保我只过滤掉下面的人 B?

currentIndex关于状态的文档UnkeyedDecodingContainer

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

似乎如果您尝试使用 过滤解码失败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")])
4

0 回答 0