如何在Swift中解析Alamofire API的JSON响应?

编程入门 行业动态 更新时间:2024-10-26 09:30:15
本文介绍了如何在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响应?

本文发布于:2023-11-26 01:54:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632180.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   Swift   Alamofire   API   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!