我在遍历从 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()
}
最佳答案
volumeInfo
是Dictionary
所以你需要像[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/