Skip to content

Instantly share code, notes, and snippets.

@DhavalDobariya86
Last active April 11, 2020 20:35
Show Gist options
  • Save DhavalDobariya86/082c107fc93700afb80d61a91df36f04 to your computer and use it in GitHub Desktop.
Save DhavalDobariya86/082c107fc93700afb80d61a91df36f04 to your computer and use it in GitHub Desktop.
Codable to decode required properties only from deeply nested JSON
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": "example@xyz.com",
"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