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

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

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

        }

https://stackoverflow.com/questions/26114831/

相关文章:

javascript - 如何动态创建 JavaScript 数组(JSON 格式)?

android - 如何在 Android 中解析 JSON?

json - 如何在结构中定义多个名称标签

android - 如何在 Android 中使用 HTTPClient 以 JSON 格式发送 P

c# - JSON.net:如何在不使用默认构造函数的情况下反序列化?

arrays - YAML 等效于 JSON 中的对象数组

mysql - 在 MySQL 中以 JSON 格式存储数据

c# - 在 JSON.NET 中反序列化的转换接口(interface)

javascript - 通过 JavaScript 动态创建 JSON 对象(没有连接字符串)

json - REST API - 文件(即图像)处理 - 最佳实践