2017-01-29 5 views
0

URL http://jsonplaceholder.typicode.com/usersから取得しているJSONファイルからデータを解析しようとしています。私は次に、以下のコードを使用し、JSONからの情報は、ファイルのすべての情報をコンソールに出力します。すぐにJSONを解析するための基本

let url = URL(string: "http://jsonplaceholder.typicode.com/users") 
let task = URLSession.shared.dataTask(with: url!){ (data, response, error) in 
     if error != nil 
     { 
      print("Error") 
     } 
     else 
     { 
      if let content = data 
      { 
       do 
       { 
        let readableValues = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject 
        print(readableValues) 

        if let userInfo = readableValues[0] as? NSDictionary 
        { 
         if let Name = userInfo["name"] 
         { 
          print(Name) 

         } 
        } 
       } 
       catch{ 

       } 
      } 
     } 
    } 
    task.resume() 
} 

print(readableValues)は、ファイル全体を印刷し、print(Name)は、辞書からの最初の項目から名前を印刷します。私は、ファイルからすべての名前を取得するためにreadableValuesを反復することはできません。 私はそれを取得したら、私はテーブルビューに値を取得し、新しい行に各名前を持つことができるように配列を設定する必要があります。

+1

[スウィフトブログ:スウィフトにJSONを使用した作業](https://developer.apple.com/swift/ blog /?id = 37) – vadian

答えて

0

すべてのJSONオブジェクトは、配列または辞書です。あなたは、Webサービスの出版社からそれを学びます。あなたのケースでは、それは(5月は、独自の配列や辞書が含まれています)辞書の配列です:

class TableViewController: UITableViewController { 
    var jsonValues = [[String: AnyObject]]() 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     let url = URL(string: "https://jsonplaceholder.typicode.com/users") 

     let task = URLSession.shared.dataTask(with: url!){ (data, response, error) in 
      if error != nil 
      { 
       print("Error") 
      } 
      else 
      { 
       if let content = data 
       { 
        do 
        { 
         let jsonObject = try JSONSerialization.jsonObject(with: content, options: []) 

         // Check that your jsonObject is an array of dictionaries 
         // The code below provides a quiet exit. You may replace it with an 
         // exception throw 
         guard let readableValues = jsonObject as? [[String: AnyObject]] else { 
          print("Unexpected format") 
          return 
         } 

         print("Data loaded. Assign to instance's property") 
         self.jsonValues = readableValues 

         // Any method that updatins the UI should be called from the main thread 
         // Otherwise you will get delay in refreshing the table (you have to pull 
         // the table up or down first for it to refresh) 
         DispatchQueue.main.async { 
          self.tableView.reloadData() 
         } 
        } 
        catch { 

        } 
       } 
      } 
     } 
     task.resume() 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
    } 

    override func numberOfSections(in tableView: UITableView) -> Int { 
     return 1 
    } 

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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") else { 
      fatalError("Cannot find cell with identifier 'Cell'") 
     } 

     cell.textLabel?.text = jsonValues[indexPath.row]["name"] as? String 
     return cell 
    } 
} 
+0

それでは、テーブルビューに行を設定するために外部値を作成する必要がありますか? – Ingelbert

+0

はい。 View Controllerのインスタンス変数に 'readableValues'を設定し、テーブル上で' reloadData'を呼び出す必要があります –

+0

インスタンス変数を使用しようとしていますが、印刷する値を取得できません。 – Ingelbert

関連する問題