Skip to content

Instantly share code, notes, and snippets.

@Kilo-Loco
Last active February 16, 2023 14:15
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kilo-Loco/9301aff792d38a0bcf2e04784971ef1d to your computer and use it in GitHub Desktop.
Save Kilo-Loco/9301aff792d38a0bcf2e04784971ef1d to your computer and use it in GitHub Desktop.
Decoding nested objects with dynamic keys
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)
}
@oguzhanvarsak
Copy link

This helped me a lot. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment