arraysjsonswiftswift4jsondecoder

Decoding JSON without keys in Swift


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

[
  "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...


Solution

  • 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)
    }