json 遍历 Google 本书 API

json traverse for Google Books API

我在遍历从 Google 本书 API 中检索到的 JSON 时遇到问题。

我能够从 "items" 遍历并打印 "id" 但是我如何进一步向下 json 打印 "title" 从 "volumeInfo"?

感谢任何提示或指示。

JSON 来自 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代码

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()
}

volumeInfoDictionary 所以你需要像 [String: AnyObject] 一样转换它,然后从那个 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"])
    }
}