自定义嵌套对象的Swift编码技术?

时间:2019-01-24 09:08:36

标签: ios swift

我需要获取嵌套对象的编码

class person {
var name: String?
var phone: String?
var address: Address?
}

class Address {
var area: String?
var city: String?
}

我尝试了

let data = try? JSONEncoder().encode(person)
let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: Any]

但是地址键值对没有得到。

2 个答案:

答案 0 :(得分:3)

只需实施Encodable

class Person: Encodable {
  var name: String?
  var phone: String?
  var address: Address?
}

class Address: Encodable {
  var area: String?
  var city: String?
}
let address = Address()
address.area = "Area"
address.city = "City"
let person = Person()
person.name = "name"
person.address = address

let encoded = try JSONEncoder().encode(person)

答案 1 :(得分:1)

struct Person: Encodable {
    var name, phone: String
    var address: Address
}

struct Address: Encodable {
    var area, city: String
}
  • 使您需要编码为协议Encodable的模型符合
  • 类型应以大写字母开头
  • 如果您确定不会有nil属性,请不要将它们设为可选内容
  • 您可以使模型结构代替类

然后只编码您的对象

let data = try? JSONEncoder().encode(person)

当您需要打印编码数据时,需要将它们转换为String

let data = try! JSONEncoder().encode(person)
let json = String(data: data, encoding: .utf8) ?? ""

如果您需要使用键"person"对对象进行编码并且将人员对象作为值进行编码,请对字典进行编码

let data = try! JSONEncoder().encode(["person": person])
let json = String(data: data, encoding: .utf8) ?? ""