2016-08-20 3 views
1

Google 도서 API에서 검색된 JSON을 트래버스하는 데 문제가 있습니다.Google 도서 API에 대한 json traverse

"items"에서 "id"를 트래버스하고 인쇄 할 수 있지만 "volumeInfo"에서 "title"을 인쇄하려면 어떻게해야합니까?

어떤 조언이나 조언을 부탁드립니다. 구글에서

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" 
], 

스위프트 코드

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 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"]) 
    } 
} 
+0

감사합니다. – Vxed

관련 문제