I have a struct which contains an optional metaData field of type [String: Any]?
. I'd like to parse a JSON to that struct and explicitly not map the dictionary but keep it as is.
struct MyObject: Decodable {
let id: String
let whatever: String
let metaData: [String: Any]?
enum CardKeys: String, CodingKey {
case id
case whatever
case metaData
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CardKeys.self)
id = try container.decode(String.self, forKey: .id)
whatever = try container.decode(String.self, forKey: .whatever)
metaData = try container.decodeIfPresent([String: Any].self, forKey: .metaData)
}
}
That code compiles and starts but fails at runtime. I guess that [String: Any]
just is not an valid type I can use here. But how would I do it then?