Decoding a JSON without keys in Swift 4

davidg picture davidg · Mar 7, 2018 · Viewed 7.8k times · Source

I'm using an API that returns this pretty horrible JSON:

[
  "A string",
  [
    "A string",
    "A string",
    "A string",
    "A string",
    …
  ]
]

I'm trying to decode the nested array using JSONDecoder, but it doesn't have a single key and I really don't know where to start… Do you have any idea?

Thanks a lot!

Answer

fl034 picture fl034 · Mar 7, 2018

If the structure stays the same, you can use this Decodable approach.

First create a decodable Model like this:

struct MyModel: Decodable {
    let firstString: String
    let stringArray: [String]

    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        firstString = try container.decode(String.self)
        stringArray = try container.decode([String].self)
    }
}

Or if you really want to keep the JSON's structure, like this:

struct MyModel: Decodable {
    let array: [Any]

    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        let firstString = try container.decode(String.self)
        let stringArray = try container.decode([String].self)
        array = [firstString, stringArray]
    }
}

And use it like this

let jsonString = """
["A string1", ["A string2", "A string3", "A string4", "A string5"]]
"""
if let jsonData = jsonString.data(using: .utf8) {
    let myModel = try? JSONDecoder().decode(MyModel.self, from: jsonData)
}