Search code examples
jsonswiftswift3alamofire

Get array key value with Alamofire


I am making a simple request to get specific data from a JSON file, but I am having issues getting the exact data.

The JSON file:

{
    "Something1": {
        "Added": "09-10-2016",
        "Expires": "09-12-2016",
        "Reliability": "78%",
        "Views": "2",
        "Priority": "High"
    },
    "Something2": {
        "Added": "09-11-2016",
        "Expires": "09-13-2016",
        "Reliability": "98%",
        "Views": "5",
        "Priority": "Low"
    }
}

The swift code:

Alamofire.request("https://example.com/args.json").responseJSON { response in
            if let JSON = response.result.value as? [String:AnyObject] {
                print(JSON["Something1"])
            }
        }

With print(JSON["Something1"]), it prints everything for Something1 just like it's supposed to but an error is thrown when I try to do print(JSON["Something1"]["Views"]) for example. How would I go about fixing this?


Solution

  • Your problem isn't related to Alamofire I'm afraid, it's more of deal with JSON using Swift. In your case when you make your first optional binding you're converting to a [String: AnyObject] and it's correct and this implies that you can subscript JSON["Something1"].

    But after that when you try to subscript again over the JSON["Something1"]["Views"] the compiler doesn't know what have the JSON["Something1"] so you can't using as a dictionary instead you need to cast it again to a dictionary because is nested using optional binding like this:

    if let nestedDictionary1 = JSON["Something1"] as? [String: AnyObject] {
        // access individual value in dictionary
    
        if let views = nestedDictionary1["Views"] as? Int {
             print(views)
        }
    }
    

    You can read more about the work with JSON in this article of Apple.

    I hope this help you.