简体   繁体   English

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

[英]Swift Encoding Technique for Custom nested Objects?

I am need to get encoding for the nested object我需要获取嵌套对象的编码

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

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

I tried我试过

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

but Address key value pair is not getting.但地址键值对没有得到。

Just implement Encodable只需实现可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
}
  • conform your models which you need to encode to protocol Encodable使您需要编码的模型符合Encodable协议
  • types should start with big capital letter类型应以大写字母开头
  • if you're sure that properites won't be nil don't make them optional如果您确定属性不会nil请不要将它们设为可选
  • you can make your models structs instead of classes你可以让你的模型结构而不是类

Then just encode your object然后只需对您的对象进行编码

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

When you need print your encoded data, you need to convert them to String当您需要打印编码数据时,您需要将它们转换为String

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

if you need to encode object with key "person" and person object as value, encode dictionary如果您需要使用键"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