Swift-嵌套对象的JSON序列化

时间:2018-06-30 10:18:24

标签: ios json swift serialization

我有一个从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
   }
}

2 个答案:

答案 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

假设这是您的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到数据

要进行测试,我们将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")