我有一个从JSON创建的对象(序列化)。该对象具有一个id属性,该属性表示系统中存储的另一个对象。如何在序列化过程中获取嵌套对象?
import UIKit
class Person: Codable {
let firstName: String
let lastName: String
let addressId: String
let address: Address // How to create it during serialisation
private enum CodingKeys: String, CodingKey {
case firstName
case lastName
case addressId = "addressId"
}
init(firstName: String, lastName: String, addressId:String) {
self.firstName = firstName
self.lastName = lastName
self.addressId = addressId
}
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.firstName = try values.decode(String.self, forKey: .firstName)
self.lastName = try values.decode(String.self, forKey: .lastName)
self.addressId = try? values.decode(URL.self, forKey: .addressId)
}
}
struct PersonsList : Codable {
let persons: [Person]
}
class Address {
static func getAddress(addressId: String) -> Address
{
//some code
return address
}
}
答案 0 :(得分:0)
使用惰性属性进行操作
编辑
选项1
lazy var address:Address = { [unowned self] in
return Address.getAddress(addressId: self.addressId)
}()
选项2
var adreess1:Address {
return Address.getAddress(addressId: self.addressId)
}
答案 1 :(得分:0)
假设这是您的json
let json = """
[
{
"firstName": "James",
"lastName": "Kirk",
"address": { "id": "efg" }
}
]
"""
您可以简化定义模型的方式
struct Person: Codable {
let firstName: String
let lastName: String
let address: Address
struct Address: Codable {
let id: String
}
}
如您所见,无需编写自定义
init(:from)
要进行测试,我们将json转换为Data
值。
let data = json.data(using: .utf8)!
最后我们可以解码数据
if let persons = try? JSONDecoder().decode([Person].self, from: data) {
print(persons.first?.address.id)
}
输出
Optional("efg")