【问题标题】:json traverse for Google Books APIGoogle Books API 的 json 遍历
【发布时间】:2016-08-20 20:47:33
【问题描述】:

我在遍历从 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()
}

【问题讨论】:

    标签: json swift google-books


    【解决方案1】:

    volumeInfoDictionary,因此您需要将其转换为[String: AnyObject],然后从该volumInfo Dictionary 中获取title

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

    【讨论】:

    • 谢谢,这正是我所需要的。
    猜你喜欢
    • 2014-12-31
    • 1970-01-01
    • 2015-11-13
    • 2023-03-22
    • 2021-10-22
    • 2019-06-21
    • 2012-11-05
    • 2017-09-07
    • 1970-01-01
    相关资源
    最近更新 更多