Search code examples
swiftjsondecoder

How to parse below dynamic JSON in swift 4.2?


{
  "payload": {
    “key1”: “value1”,
    “key2”: "{\"command\": \"playSound\",\"tone\": 0,\"delay\": 100000}”,
    “key3”: 0
  },
}

Above is my response data, whereas 'payload' is known key but inside 'payload' all keys & values are unknown.

e.g. 'key1' can be any name and value of 'key1' can be anything (Int/String/Dictionary).

My code is like below, but it doesn't work.

let decoder = JSONDecoder()
do {
    let dict = try! decoder.decode([String: Any].self, from: data!)
    complete(true, dict, nil)
}

Any idea?


Solution

  • One option is to fall back to the old JSONSerialization, but the downside is you lose the Decodable support for the known keys on the top level.

    Another option is to implement the init(from: Decoder) method of your outer object (the one that has payload), and manually decode the dictionary there.

    Or there are Codable-conforming wrappers that you can use instead of Any. Here is one (disclaimer: I am the author).