Decoding a JSON without keys in Swift 4

前端 未结 3 1320
别跟我提以往
别跟我提以往 2021-02-01 05:49

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

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


        
3条回答
  •  独厮守ぢ
    2021-02-01 06:04

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

提交回复
热议问题