Encodable & Decodable [Part-2]
[continued from here]
Let’s consider below JSON fragment for digging into the concept:
{
"firstname": "John",
"lastname": "Doe",
"age": 20,
"job_information" : {
"title": "iOS Developer",
"salary": 5000
},
}
Encodable 📦
A type that Encode itself to an external representation by implementation of Encodable protocol.
Let’s look deeper into by programming a structPerson
struct Person: Encodable {
var firstName: String
var lastName: String
var age: Int
var jobInfo: JobInformation init(firstName: String, lastName: String, age: Int, jobInfo: Job) {
self.firstName = firstName
self.lastName = lastName
self.age = age
self.jobInfo = jobInfo
}
}
struct Job: Encodable {
var title: String
var salary: Int init(title: String, salary: Int) {
self.title = title
self.salary = salary
}
}let person1 = Person(firstName: "John", lastName: "Doe", age: 20, jobInfo: JobInformation(title: "iOS Developer", salary: 5000))
let encoded = try JSONEncoder().encode(person1)//String(data: encoded, encoding: .utf8)
//we get back the json which we encoded in string below:
{
"firstname": "John",
"lastname": "Doe",
"age": 20,
"job_information" : {
"title": "iOS Developer",
"salary": 5000
},
}
Before, jumping into Decodable let’s quickly analyse that we need key pairs for decoding values. So, we can include them with enums into the Types itself
CodingKeys.
CodingKeys
allows you to use specific variable names to represent your JSON keys.
Codable types can declare a special nested enumeration named CodingKeys
that conforms to the CodingKey
protocol.
The example below uses alternative keys for the name
and dob
properties of the Person
structure when encoding and decoding:
struct Person: Codable {
var firstName: String
var lastName: String
var age: Int
enum CodingKeys: String, CodingKey {
case firstName = "firstname"
case lastName = "lastname"
case age = "age"
}
}
Decodable 📤
A type that can decode itself from an external representation.
In the example below, the Job
structure is extended to conform to the Decodable
protocol by implementing its required initializer, init(from:)
:
And similarly Person includes Job instance type, which inherits the encoded value while its initialized.