繁体   English   中英

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

[英]Swift Encoding Technique for Custom nested Objects?

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

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]

但地址键值对没有得到。

只需实现可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)
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"和person对象作为值对对象进行编码,请编码字典

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM