2017-03-08 6 views
-1

reddit에서 일부 Json 데이터를 구문 분석하고 테이블보기에 정보를 표시하는 방법을 찾으려고합니다. (https://api.reddit.com). 는 지금까지 내 코드는 모습입니다 :Reddit : 신속한 JSON 구문 분석 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

첫째는 그 사용 URLSession 대신 Main 스레드를 차단하기 때문에 URL에서 JSON를 얻을 수 Data(contentsOf:)를 사용하지 마십시오.

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 (파운데이션)의 JSON 파싱은 간단합니다. JSONSerialization.jsonObject(with:)으로 전화하면 "오브젝트 그래프"가 다시 나타납니다. 일반적으로 다른 객체를 포함하는 사전 또는 배열입니다. 결과를 적절한 유형으로 캐스팅하고 객체 그래프를 탐색하려면 얻는 데이터 형식에 대해 알아야합니다. 캐스트를 잘못하면 코드가 예상대로 실행되지 않습니다. JSON 데이터를 표시해야합니다. JASON과 코드가 일치하지 않는 것 같습니다. 의