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
}
Encodable
nil
don't make them optionalThen 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.