Swift 4. I\'m in a very similar situation than Using Codable on a dynamic type/object but for me the changing variable is the name of the dictionary and not the keys inside. It
If you already know all the keys in the inner JSON, use a struct to take advantage of static typing. Assuming that there's only 1 key on the top level in your JSON (your customName
key):
struct MyModel: Decodable {
struct InnerModel: Decodable {
var constantKey1: Double
var constantKey2: Double
}
var customName: InnerModel
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: GenericCodingKeys.self)
// Assume that there's only 1 key at the top level in the JSON
if let key = container.allKeys.first {
customName = try container.decode(InnerModel.self, forKey: key)
} else {
throw NSError(domain: NSCocoaErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "JSON is empty"])
}
}
}