迅速编码地图儿童通过ID



我有以下代码。

import Foundation
let jsonData = """
[
    {"id": "1", "firstname": "Tom", "lastname": "Smith", "age": "28"},
    {"id": "2", "firstname": "Bob", "lastname": "Smith"},
    {"id": "3", "firstname": "Jim", "lastname": "Smith", "parentid": "2"},
    {"id": "4", "firstname": "Ray", "lastname": "Smith", "parentid": "3"}
]
""".data(using: .utf8)!
class Person: Codable {
    let id: String
    let firstName, lastName: String
    let age: String?
    let parentid: String?
    let children: [Person]?
    enum CodingKeys : String, CodingKey {
        case firstName = "firstname"
        case lastName = "lastname"
        case age
        case parentid
        case id
    }
    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        firstName = try values.decode(String.self, forKey: .firstName)
        lastName = try values.decode(String.self, forKey: .lastName)
        age = try values.decodeIfPresent(String.self, forKey: .age)
        parentid = try values.decodeIfPresent(String.self, forKey: .parentid)
        id = try values.decodeIfPresent(String.self, forKey: .id)
    }
}
let decoded = try JSONDecoder().decode([Person].self, from: jsonData)
print(decoded)

所以我有children属性。我基本上希望decoded是一个具有2个Person对象(Tom and Bob)的数组。decoded[1].children应该是一个具有1 Person对象(JIM)的数组。decoded[1].children[0]应该是一个具有1 Person对象的数组(ray)。

如何使用Swift Codable系统来实现此目标?

您可以做类似:

的事情
    if let decoded = try? JSONDecoder().decode([Person].self, from: jsonData)
    {
        for person in decoded
        {
            person.children = decoded.filter({ (child) -> Bool in
                return person.id == child.parentid
            })
        }
    }

在上面的代码中,在获得decoded数组后,我只是使用for loop横穿它,以识别每个person的CC_11(如果存在)。

相关内容

  • 没有找到相关文章

最新更新