2017-06-14 123 views
-3

得到了下面的json!我試圖從圖像數組中的那些樹中獲取單個url!我失敗了很多......任何人都可以請解釋我爲什麼以及如何得到它。解析數組swift中的json數組

<code> 
    let dataTask = session.dataTask(with: request) { (data, response, error) in  
     do { 
      let json = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String : AnyObject] 

      if let artists = json?["artists"] as? [String: AnyObject]{ 

       if let items = artists["items"] { 

        for i in 0..<items.count { 

         let item = items[i] as? [String: AnyObject] 

         let name = item? ["name"] as! String 

         self.nameArray.append(name) 

         let popularity = item? ["popularity"] as! Int 

         self.popuArray.append(popularity) 

         if let artists = item["artists"] as? String: AnyObject{ 

          if let images = artists["images"] as? [String: AnyObject] { 

          let imageData = images[0] 
           } 
          } 

         print(name) 

         print(popularity) 
         } 
       } 

      } 
</code>  

我能夠從名字和人氣得到的價值!沒有辦法爲這個URL ...裏面的圖像! 我的JSON是Spotify的.. API

是這樣的:

{ "artists" : { "href" : " https://api.spotify.com/v1/search?query=Metallica&type=artist&market=CA&offset=0&limit=20 ", "items" : [ { "external_urls" : { "spotify" : " https://open.spotify.com/artist/2ye2Wgw4gimLv2eAKyk1NB " }, "followers" : { "href" : null, "total" : 3455148 }, "genres" : [ "alternative metal", "alternative rock", "hard rock", "metal", "rock", "speed metal", "thrash metal" ], "href" : " https://api.spotify.com/v1/artists/2ye2Wgw4gimLv2eAKyk1NB ", "id" : "2ye2Wgw4gimLv2eAKyk1NB", "images" : [ { "height" : 640, "url" : " https://i.scdn.co/image/5a06711d7fc48d5e0e3f9a3274ffed3f0af1bd91 ", "width" : 640 }, { "height" : 320, "url" : " https://i.scdn.co/image/0c22030833eb55c14013bb36eb6a429328868c29 ", "width" : 320 }, { "height" : 160, "url" : " https://i.scdn.co/image/c1fb4d88de092b5617e649bd4c406b5cab7d3ddd ", "width" : 160 } ], "name" : "Metallica", "popularity" : 83, "type" : "artist", "uri" : "spotify:artist:2ye2Wgw4gimLv2eAKyk1NB" },

我要挑我從那些3.

回答

0

看來任何你想要的網址只需要更新這線..

if let images = artists["images"] as? [String: AnyObject] { 

if let images = artists["images"] as? [[String: AnyObject]] { 
    if let firstImage = images.first, let urlString = firstImage["url"] as? String { 
     let url = URL(string: urlString) 
    } 
} 

[String:AnyObject]蒙上Dictionary對象,[[String:AnyObject]]投射到字典對象的數組這是你在這種情況下,需要什麼