如何在 Swift 中解析来自 Alamofire API 的 JSON 响应?
问题描述:
我编写的以下代码也得到了 JSON 格式的响应,但 JSON 的类型是AnyObject",我无法将其转换为 Array 以便我可以使用它.
Following code I have written and I am getting response in JSON also but the type of JSON is "AnyObject" and I am not able to convert that into Array so that I can use that.
Alamofire.request(.POST, "MY URL", parameters:parameters, encoding: .JSON) .responseJSON
{
(request, response, JSON, error) in
println(JSON?)
}
答
Swift 2.0 Alamofire 3.0 的答案实际上应该看起来更像这样:
The answer for Swift 2.0 Alamofire 3.0 should actually look more like this:
Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON).responseJSON
{ response in switch response.result {
case .Success(let JSON):
print("Success with JSON: (JSON)")
let response = JSON as! NSDictionary
//example if there is an id
let userId = response.objectForKey("id")!
case .Failure(let error):
print("Request failed with error: (error)")
}
}
Alamofire 4.0 和 Swift 3.0 的更新:
UPDATE for Alamofire 4.0 and Swift 3.0 :
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { response in
print(response)
//to get status code
if let status = response.response?.statusCode {
switch(status){
case 201:
print("example success")
default:
print("error with response status: (status)")
}
}
//to get JSON return value
if let result = response.result.value {
let JSON = result as! NSDictionary
print(JSON)
}
}