2016-08-20 41 views
1

我遇到了遍歷從Google圖書API檢索的JSON的問題。針對Google圖書API的json遍歷

我可以遍歷並打印「項目」中的「id」,但是如何進一步查看json以打印「volumeInfo」中的「標題」?

任何提示或指針讚賞。

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

回答

1

volumeInfoDictionary所以你需要投像[String: AnyObject],然後從那個volumInfo Dictionarytitle

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

謝謝,這正是我所需要的。 – Vxed