ios - 如何在 Swift 中解析来自 Alamofire API 的 JSON 响应?

标签 ios json swift alamofire

以下代码是我编写的,我也得到了 JSON 格式的响应,但 JSON 的类型是“AnyObject”,我无法将其转换为数组以便我可以使用它。

Alamofire.request(.POST, "MY URL", parameters:parameters, encoding: .JSON) .responseJSON
{
    (request, response, JSON, error) in

    println(JSON?)
}

最佳答案

Swift 2.0 Alamofire 3.0 的答案实际上应该看起来更像这样:

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 更新:

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)
            }

        }

关于ios - 如何在 Swift 中解析来自 Alamofire API 的 JSON 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55978204/

相关文章:

当 Podfile 具有 'use_frameworks!' 选项时,iOS 应用程序崩溃

python - 为什么protobuf的内存比python中的普通dict+list小?

swift - 具有多个 hashKeyValues 的 AWS DynamoDB Swift 查询

ios - 下载图像数据时显示进度的最简单方法是什么? [ swift ]

ios - 在 ios swift 3.0 中解析 json 对象数组

swift - 覆盖 URL 的公共(public)初始值设定项

ios - 如何在 UITableView 处于编辑模式时隐藏条形按钮项目? ( swift )

ios - 如何在不重启 ios 设备的情况下加载 launchDaemon.plist?

iphone - 我如何通过xcode搜索iphone中的所有声音文件

php - 解析 JSON 数据时出错。 JSONException : End of input at character