Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to handle json reponse in swift 3 | xcode 8 | alamofire 4.0 #1647

Closed
yokesharun opened this issue Sep 30, 2016 · 3 comments
Closed

How to handle json reponse in swift 3 | xcode 8 | alamofire 4.0 #1647

yokesharun opened this issue Sep 30, 2016 · 3 comments
Assignees
Labels

Comments

@yokesharun
Copy link

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

@ghost
Copy link

ghost commented Oct 1, 2016

            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"]

@grosch
Copy link

grosch commented Oct 1, 2016

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
        }

@cnoon
Copy link
Member

cnoon commented Oct 1, 2016

Thanks @grosch! 馃嵒

@cnoon cnoon closed this as completed Oct 1, 2016
@cnoon cnoon added the support label Oct 1, 2016
@cnoon cnoon self-assigned this Oct 1, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants