Google Books API 的 json 遍历

标签 json swift google-books

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

我能够遍历并打印“items”中的“id”,但我如何进一步深入 json 以打印“volumeInfo”中的“title”?

感谢任何提示或指示。

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

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]一样转换它, 然后得到 title从那个 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"])
    }
}

关于Google Books API 的 json 遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39054180/

相关文章:

Javascript 对象处理困惑

c# - System.Text.Json 中 Newtonsoft.Json DefaultValueHandling = DefaultValueHandling.Ignore 选项的等价物是什么

ios - Command/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang 退出失败

android - Android 上的 Google Book Api 访问失败

ios - 当我在搜索栏中键入以检索 Google 图书信息时,我的表格 View 没有重新加载

json - 使用Elastic Search搜索多个词

javascript - 我想在 reactJs 中显示 JSON 结果

Swift 2迁移错误: "Type of expression is ambiguous without more context "

c - Swift 3 中的 GLFW 回调签名