关于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<Person>) in
print(response)
}
目前 Alamofire 4 不支持 Codable(参见 #2177),你可以使用这个扩展来实现: 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)
示例:http://swift.sandbox.bluemix.net/#/repl/59a4b4fad129044611590820
使用CodableAlamofire:
let decoder = JSONDecoder()
Alamofire.request(url).responseDecodableObject(keyPath: nil, decoder: decoder) { (response: DataResponse<[Person]>) in
let persons = response.result.value
print(persons)
}
keypath
对应于 JSON 结构中包含结果的路径。例如:
{
"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
(空的keypath
会抛出异常)
{"firstname": "Tom", "lastname": "Smith", "age": 31}
和一个人类,我可以使用可编码将JSON转换为Swift中的Person对象。但是,如果我有从Alamofire获取的JSON数组,我不确定该怎么做。 - Charlie Fish