Alamofire: How to handle json reponse in swift 3 | xcode 8 | alamofire 4.0

Created on 30 Sep 2016  ·  3Comments  ·  Source: Alamofire/Alamofire

Alamofire.request("https://httpbin.org/get").responseJSON { response in
debugPrint(response)

            if let json = response.result.value {
                let ip = json["url"] as! String
            }
        }

Error : 👎 Type 'Any' has no subscript members

support

Most helpful comment

This is how I always handle my JSON responses.

.responseJSON {
    response in

    switch response.result {
    case .failure(let error):
        // Do whatever here
        return

    case .success(let data):
        // First make sure you got back a dictionary if that's what you expect
        guard let json = data as? [String : AnyObject] else {
            NSAlert.okWithMessage("Failed to get expected response from webserver.")
            return
        }

        // Then make sure you get the actual key/value types you expect
        guard var points = json["points"] as? Double,
            let additions = json["additions"] as? [[String : AnyObject]],
            let used = json["used"] as? [[String : AnyObject]] else {
                NSAlert.okWithMessage("Failed to get data from webserver")
                return
        }

All 3 comments

            if response.result.value is NSNull {
                return
            }
            let JSON = response.result.value as? NSDictionary
            let id = JSON?["id"] as! String

I think you need the ? before ["url"]

This is how I always handle my JSON responses.

.responseJSON {
    response in

    switch response.result {
    case .failure(let error):
        // Do whatever here
        return

    case .success(let data):
        // First make sure you got back a dictionary if that's what you expect
        guard let json = data as? [String : AnyObject] else {
            NSAlert.okWithMessage("Failed to get expected response from webserver.")
            return
        }

        // Then make sure you get the actual key/value types you expect
        guard var points = json["points"] as? Double,
            let additions = json["additions"] as? [[String : AnyObject]],
            let used = json["used"] as? [[String : AnyObject]] else {
                NSAlert.okWithMessage("Failed to get data from webserver")
                return
        }

Thanks @grosch! 🍻

Was this page helpful?
0 / 5 - 0 ratings