简体   繁体   中英

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

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
  • types should start with big capital letter
  • if you're sure that properites won't be nil don't make them optional
  • 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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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