Skip to content

Instantly share code, notes, and snippets.

@KevinGutowski
Last active December 23, 2020 08:26
Show Gist options
  • Save KevinGutowski/18c9712645c3830e92697b3aa810c933 to your computer and use it in GitHub Desktop.
Save KevinGutowski/18c9712645c3830e92697b3aa810c933 to your computer and use it in GitHub Desktop.
Decode JSON with Dynamic Keys using Decodable
// https://swiftsenpai.com/swift/decode-dynamic-keys-json/
// https://stackoverflow.com/questions/49549691/how-to-handle-dynamic-keys-from-json-response-using-swift-4-coding-keys
import Foundation
let json = """
{
"name": "Avengers High",
"students": {
"S001": {
"firstName": "Tony",
"lastName": "Stark"
},
"S002": {
"firstName": "Peter",
"lastName": "Parker"
},
"S003": {
"firstName": "Bruce",
"lastName": "Wayne"
}
}
}
"""
let data = Data(json.utf8)
struct GenericCodingKeys: CodingKey {
var stringValue: String
var intValue: Int?
init?(intValue: Int) {
self.intValue = intValue
self.stringValue = "\(intValue)"
}
init?(stringValue: String) {
self.stringValue = stringValue
}
}
struct Student: Decodable {
let firstName: String
let lastName: String
}
struct School: Decodable {
let name: String
var students: [Student]
private enum CodingKeys: CodingKey {
case name, students
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decode(String.self, forKey: .name)
self.students = [Student]()
let subContainer = try container.nestedContainer(keyedBy: GenericCodingKeys.self, forKey: .students)
for key in subContainer.allKeys {
let student = try subContainer.decode(Student.self, forKey: key)
self.students.append(student)
}
}
}
let decodedResult = try! JSONDecoder().decode(School.self, from: data)
print(decodedResult.students[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment