json遍历Google Books API

时间:2016-08-20 12:31:31

标签: json swift google-books

我在浏览从Google Books API检索到的JSON时遇到问题。

我可以遍历和打印" id"来自" items"但是我如何进一步了解json以打印"标题"来自" volumeInfo"?

任何提示或指示赞赏。

来自Google的JSON:

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

1 个答案:

答案 0 :(得分:1)

volumeInfoDictionary,因此您需要像[String: AnyObject]一样投放,然后从该volumInfo title获取Dictionary

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