0

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?

Funkybit
  • 359
  • 1
  • 2
  • 15
  • Related: [How to decode a nested JSON struct with Swift Decodable protocol?](https://stackoverflow.com/questions/44549310/how-to-decode-a-nested-json-struct-with-swift-decodable-protocol). – Martin R Oct 26 '17 at 14:04
  • `Decodable` was not designed with dynamic keys in mind. You can work around it, but the better approach is to define a `MyMetadata` struct with all possible metadata as optional properties – Code Different Oct 26 '17 at 14:26

1 Answers1

0

I created a framework to decode/encode dictionaries.

CodableDictionary

Install framework and replace

  let metaData: [String: Any]?

with

  let metaData: CodableDictionary?
Stefan Wieland
  • 246
  • 2
  • 4