如何在 Swift 中解析来自 Alamofire API 的 JSON 响应? [英] How to parse JSON response from Alamofire API in Swift?

查看:27
本文介绍了如何在 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)")
                }
    }

https://github.com/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 响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆