我有以下代码。
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(如果存在)。