我需要获取嵌套对象的编码
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]
但是地址键值对没有得到。
答案 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) ?? ""