Last active
February 16, 2023 14:15
-
-
Save Kilo-Loco/9301aff792d38a0bcf2e04784971ef1d to your computer and use it in GitHub Desktop.
Decoding nested objects with dynamic keys
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 Foundation | |
// JSON response converted to Data | |
let response = """ | |
{ | |
"name": "Kilo Loco", | |
"pets": { | |
"0": { | |
"name": "Doggo" | |
}, | |
"1": { | |
"name": "Kitty" | |
} | |
} | |
} | |
""" | |
.data(using: .utf8)! | |
// Nested object type that is Codable | |
struct Pet: Codable { | |
let name: String | |
} | |
// The object that represents the Response | |
struct User: Codable { | |
let name: String | |
let pets: [Pet] | |
// The response is not returning an array as the | |
// User object expects, so we need to manually handle | |
// how the response will be decoded | |
init(from decoder: Decoder) throws { | |
let container = try decoder.container(keyedBy: CodingKeys.self) | |
self.name = try container.decode(String.self, forKey: .name) | |
// We can decode anything that is Decodable, and that | |
// applies to dictionaries with Decodable Keys and | |
// Values | |
let petsDict = try container.decode([String: Pet].self, forKey: .pets) | |
self.pets = petsDict.map { $0.value } | |
} | |
} | |
do { | |
// Decode as usual | |
let user = try JSONDecoder().decode(User.self, from: response) | |
print(user) | |
} catch { | |
print(error) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This helped me a lot. Thank you.