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

标签 ios json swift alamofire

按照我编写的代码,我也收到了 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)
            }

        }

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

相关文章:

ios - 如何在 iOS 视频播放器中播放 webm 文件

jquery - 生成的 JsonResult 中的属性名称大小写不一致

javascript - Echart bar不会显示使用json

ios - 以编程方式更新高度约束

iOS MKAnnotationView LongPressGestureRecognizer

ios - 如何将图像设置为具有背景颜色的图像查看中心迅速

objective-c - UIWebView 委托(delegate)中的 EXC_BAD_ACCESS

json - 不调用 Go json Unmarshaller

ios - 在 Swift 3 中使用选择器

swift - 如何使用 Swift 在 Firebase 中存储自定义对象?