2016-11-11 36 views
0

試圖獲得發佈的'標題','內容',類別的'標題'&作者姓名從這個JSON。獲得錯誤Type 'NSFastEnumerationIterator.Element' (aka 'Any') has no subscript members。在控制檯中的打印帖子工作正常,但在嘗試獲取帖子標題時出現錯誤。請幫忙。 JSON & SWITH代碼是熱修復類型'NSFastEnumerationIterator.Element'(又名'Any')沒有下標成員

JSON

{ 
    "status":"ok", 
    "count":1, 
    "count_total":44, 
    "pages":44, 
    "posts":[ 
     { 
     "id":87, 
     "url":"http://www.website.com/blogs/my first blog/", 
     "title":"My First Blog", 
     "content":"blog content", 
     "date":"2015-04-06 22:42:12", 
     "modified":"2015-12-26 00:45:09", 
     "categories":[ 
      { 
       "id":45, 
       "title":"Trip", 
       "description":"", 
       "post_count":21 
      } 
     ], 
     "author":{ 
      "id":1, 
      "name":"admin", 
      "url":"", 
      "description":"hello" 
     } 
     } 
    ] 
} 

Swift代碼

  if let blogContent = data { 

       do { 

        let jsonResult = try JSONSerialization.jsonObject(with: blogContent, options: JSONSerialization.ReadingOptions.mutableContainers) 

        if let items = jsonResult as? [NSString:Any] { 

         //print(items) 

         let item = items["posts"] as! NSArray 

         for post in item { 

          print(post) 

          print(post["title"]) 

         } 

        } 
       } catch { 

        print("JSON processing failed.") 
       } 

      } 
+0

在「相關」部分有6個問題具有相同的標題。你確定他們都不能解決你的問題嗎? –

+0

Sue提示在Swift中使用Foundation收集類型的所有教程;-) – vadian

+0

@MartinR是的,我試過了。無法找到任何可能的幫助。謝謝 – Hitz

回答

1

得到它的工作。這是工作代碼。希望它可以幫助有同樣問題的人。謝謝:)

if let blogContent = data { 

       do { 

        let jsonResult = try JSONSerialization.jsonObject(with: blogContent, options: JSONSerialization.ReadingOptions.mutableContainers) 

        if let items = jsonResult as? [String: AnyObject] { 

         if let item = items["posts"] as? NSArray { 

          for posts in item { 

           if let post = posts as? [String: AnyObject] { 

            print(post["title"]!) 

            let categories = post["categories"] as! NSArray 

            for category in categories { 

             if let categ = category as? [String: AnyObject] { 

              print(categ["title"]!) 

             } 
            } 

            let author = post["author"] as! [String: AnyObject] 

            print(author["name"]!) 

           } 

          } 

         } 
相關問題