Search code examples
jsonswiftgoogle-books

json traverse for Google Books API


I am having issues traversing a JSON retrieved from the Google Books API.

I am able to traverse and print the "id" from "items" but how do I get further down the json to print the "title" from "volumeInfo"?

Any tips or pointers appreciated.

JSON from Google:

{
 "kind": "books#volumes",
 "totalItems": 555,
 "items": [
 {
 "kind": "books#volume",
 "id": "BZXn-3QtQ_UC",
 "etag": "Phnt2wzOFMo",
 "selfLink": "https://www.googleapis.com/books/v1/volumes/BZXn-3QtQ_UC",
 "volumeInfo": {
  "title": "Revisiting Stephen King",
  "subtitle": "A Critical Companion",
  "authors": [
   "Sharon A. Russell"
 ],

Swift Code

let url = NSURL(string: "https://www.googleapis.com/books/v1/volumes?q=stephen+king")

NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in

if error != nil {
    print(error)
    return
}

do {
    let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers)

    if json is [String: AnyObject] {

        let items = json["items"] as? [[String: AnyObject]]

        for item in items! {
            let kind = item["id"] as? String

            print(kind)
        }
    }

} catch let jsonError {
    print(jsonError)
}

}.resume()
}

Solution

  • volumeInfo is Dictionary so you need to cast it like [String: AnyObject], and then get the title from that volumInfo Dictionary.

    for item in items! {
        let kind = item["id"] as? String
        print(kind)
        if let volumeInfo = item["volumeInfo"] as? [String: AnyObject] {
           print(volumeInfo["title"])
        }
    }