本文介绍了如何在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)") } }github/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md
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) } }更多推荐
如何在Swift中解析Alamofire API的JSON响应?
发布评论