0

I have the following JSON response containing a JSON dictionary:

enter image description here

What I need is to only extract the 3 categories names (only 1 shown in my screenshot, namely "Drinks", but you can see at the very top a count of 3).

I tried the following, but always get nil returned.

func getMenuCategories() {
    let headers = [
        "Api-key": apiKey
    ]

    let url = "https://xxxxxxxx/menu/categories"

    Alamofire.request(.GET, url, headers: headers, encoding: .JSON)
        .responseJSON { response in switch response.result {
                case .Success(let JSON):
                    print("Success with JSON: \(JSON)")

                    let response = JSON as! NSDictionary
                    let categories1 = response.objectForKey("_embedded")!  // always nil
                    let categories2 = response.objectForKey("categories")! // always nil

                case .Failure(let error):
                    print("Request failed with error: \(error)")
            }
    }
}

I know I get a valid response because variable JSON contains the whole response.

How can I search correctly?

ppp
  • 713
  • 1
  • 8
  • 23

2 Answers2

0

For that particular JSON you could do the following

guard let jsonData = JSON as? [String: Any],
    let embedded = jsonData["_embedded"] as? [String: Any],
    let categories = embedded["categories"] as? [[String: Any]] else {
        return
}

Now categories should have the array of [String:Any] and in your case categories[0] is going to hold the information for the one with Drinks i.e.

guard let drinksCategory = categories.first,
    let name = drinksCategory["name"] as? String else {
        return
}

Now if all is good with the JSON the name variable should have the correct information you want

darren102
  • 2,830
  • 1
  • 22
  • 24
0

to answer my own question in case this helps anyone, I ended up using valueForKeyPath as follows:

func getMenuCategories() {
    let headers = [
        "Api-key": apiKey
    ]

    let url = "https://xxxxxxxx/menu/categories"

    Alamofire.request(.GET, url, headers: headers, encoding: .JSON)
        .responseJSON { response in switch response.result {
                case .Success(let JSON):
                    print("Success with JSON: \(JSON)")

                    let jsonData = JSON as? NSDictionary
                    let categories = jsonData?.valueForKeyPath("_embedded.categories._embedded.items._embedded.menu_categories.name")

                case .Failure(let error):
                    print("Request failed with error: \(error)")
            }
    }
}
ppp
  • 713
  • 1
  • 8
  • 23