Last active
April 11, 2020 20:35
-
-
Save DhavalDobariya86/082c107fc93700afb80d61a91df36f04 to your computer and use it in GitHub Desktop.
Codable to decode required properties only from deeply nested JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
struct Employee: Decodable { | |
let name: String | |
let city: String | |
enum CodingKeys: String, CodingKey { | |
case name | |
case city | |
case contactInformation | |
case mailingAddress | |
} | |
init(from decoder: Decoder) throws { | |
let container = try decoder.container(keyedBy: CodingKeys.self) | |
name = try container.decode(String.self, forKey: .name) | |
// Get container for `ContactInformation` | |
let contactInformationContainer = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .contactInformation) | |
// Get container for `MailingAddress` | |
let mailingAddressContainer = try contactInformationContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: .mailingAddress) | |
// decode `city` from `MailingAddress` | |
city = try mailingAddressContainer.decode(String.self, forKey: .city) | |
} | |
} | |
let jsonData: Data = """ | |
{ | |
"name": "Eric", | |
"contactInformation": { | |
"phoneNumber": "+1 123123123", | |
"email": "[email protected]", | |
"mailingAddress": { | |
"city": "New York City", | |
"state": "New York", | |
"pincode": 100001 | |
} | |
} | |
} | |
""".data(using: .utf8)! | |
let employee = try! JSONDecoder().decode(Employee.self, from: jsonData) | |
print("Employee name = \(employee.name)") | |
print("Employee city = \(employee.city)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment