Swift 4 Codable Array's

前端 未结 4 1215
半阙折子戏
半阙折子戏 2021-02-02 14:04

So I have an API route that returns a JSON array of objects. For example:

[
    {\"firstname\": \"Tom\", \"lastname\": \"Smith\", \"age\": 31},
    {\"firstname\         


        
4条回答
  •  灰色年华
    2021-02-02 14:59

    Update regarding Alamofire 5: responseJSONDecodable.

    struct Person: Codable {
        let firstName, lastName: String
        let age: Int
    
        enum CodingKeys : String, CodingKey {
            case firstName = "firstname"
            case lastName = "lastname"
            case age
        }
    }
    
    Alamofire.request(request).responseJSONDecodable { (response: DataResponse) in
        print(response)
    }
    

    Alamofire 4 won't add Codable support for now (see #2177), you can use this extension instead: https://github.com/Otbivnoe/CodableAlamofire.

    let jsonData = """
    [
        {"firstname": "Tom", "lastname": "Smith", "age": 31},
        {"firstname": "Bob", "lastname": "Smith", "age": 28}
    ]
    """.data(using: .utf8)!
    
    struct Person: Codable {
        let firstName, lastName: String
        let age: Int
    
        enum CodingKeys : String, CodingKey {
            case firstName = "firstname"
            case lastName = "lastname"
            case age
        }
    }
    
    let decoded = try! JSONDecoder().decode([Person].self, from: jsonData)
    

    Sample: http://swift.sandbox.bluemix.net/#/repl/59a4b4fad129044611590820

    Using CodableAlamofire:

    let decoder = JSONDecoder()
    Alamofire.request(url).responseDecodableObject(keyPath: nil, decoder: decoder) { (response: DataResponse<[Person]>) in
        let persons = response.result.value
        print(persons)
    }
    

    keypath corresponds to the path where the results are contained in the JSON structure. E.g:

    {
        "result": {
            "persons": [
                {"firstname": "Tom", "lastname": "Smith", "age": 31},
                {"firstname": "Bob", "lastname": "Smith", "age": 28}
            ]
        }
    }
    

    keypath => results.persons

    [
        {"firstname": "Tom", "lastname": "Smith", "age": 31},
        {"firstname": "Bob", "lastname": "Smith", "age": 28}
    ]
    

    keypath => nil (empty keypath throws an exception)

提交回复
热议问题