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) ?? ""