2017-03-08 111 views
-1

我試圖找到一種方法來解析通過reddit上的一些Json數據並在表視圖中顯示信息。 (https://api.reddit.com)。 到目前爲止,這是我的代碼如下所示:Reddit:JSON在swift中解析3

var names: [String] = [] 
var comment: [String] = [] 

override func viewDidLoad() { 
     super.viewDidLoad() 
let url = URL(string: "https://api.reddit.com") 
     do{ 
      let reddit = try Data(contentsOf: url!) 
      let redditAll = try JSONSerialization.jsonObject(with: reddit, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String : AnyObject] 
      if let theJSON = redditAll["children"] as? [AnyObject]{ 
       for child in 0...theJSON.count-1 { 
        let redditObject = theJSON[child] as! [String : AnyObject] 

        names.append(redditObject["name"] as! String) 
       } 
      } 
      print(names) 
     } 

     catch{ 
      print(error) 
     } 
    } 

//Table View 
func numberOfSections(in tableView: UITableView) -> Int { 
     return 1 

    } 

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return names.count 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) 

     //Configure cells... 
     cell.textLabel?.text = names[indexPath.row] 
     cell.detailTextLabel?.text = comments[indexPath.row] 


     return cell 
    } 

我知道一個事實,信息實際上是通過「redditALL」未來不斷,但我不知道我是JSONSerialization後做的不正確。 另外,如果有某種鏈接可以幫助我更好地理解JSON解析,我將非常感激。謝謝。

+0

你可以顯示你的json數據結構嗎? –

回答

0

首先不使用Data(contentsOf:)URL得到JSON,因爲它會阻止你的Main線程而不是使用URLSession的。

現在要檢索您的children數組,您需要首先訪問data字典,因爲其中包含children。所以試試這樣。

let url = URL(string: "https://api.reddit.com") 
let task = Session.dataTask(with: url!) { data, response, error in 
    if error != nil{ 
     print(error.) 
    } 
    else 
    { 
     if let redditAll = (try? JSONSerialization.jsonObject(with: reddit, options: []) as? [String : Any], 
      let dataDic = redditAll["data"] as? [String:Any], 
      let children = dataDic["children"] as? [[String:Any]] { 

       for child in children { 
        if let name = child["name"] as? String { 
         names.append(name) 
        } 
       } 
       DispatchQueue.main.async { 
        self.tableView.reloadData() 
       } 
     } 
    } 
} 
task.resume() 
0

在Swift(Foundation)中解析JSON非常簡單。你打電話JSONSerialization.jsonObject(with:),你會得到一個「對象圖」。通常它是一個包含其他對象的字典或數組。您必須瞭解所獲得的數據格式,才能將結果轉換爲適當的類型並遍歷對象圖。如果您投錯,您的代碼將無法按預期運行。你應該向我們展示你的JSON數據。您的JASON和您的代碼可能存在不匹配。