2017-01-10 8 views
0

ローカルディスクに.jsonデータファイルがあります。Swiftのjsonファイルからデータを読み取る正しい方法は何ですか?

{ 
"employees" [ 
{ 
"Name" : "John", 
"Location" : "Austin", 
"Age" : "30" 
}, 
..... 
], 
..... 
} 

ここで、ファイルを読み込み、データをUITableViewに読み込みたいとします。私の最初の考えは、データを配列に格納し、配列を使用してテーブルにデータを格納することです。しかし、私はこれを実現するための正しい手順を見つけることができません。

方法は私がこれまで試してみました:

 let currentFileURL = URL(string: currentFileString) 
     do { 
      let currentData = try Data(contentsOf: currentFileURL!) 

      let jsonData = try JSONSerialization.jsonObject(with: currentData, options:.allowFragments) 

     //*********************************************************** 
     //How to proceed here? Or am I using the right methods above? 
     //***********************************************************    

      } catch { 
      //catch the error here 
      } 

はあなたの助けをありがとう!

ポール

答えて

1

最良の方法は、作成したカスタムclassまたはstruct、あなたtableView方法でそのカスタムクラスオブジェクトの配列を使用することです。

class Employee { 

    var name: String? 
    var location: String? 
    var age: Int? 

    init?(dictionary: [String: String]) } 
     if let name = employee["Name"], let location = employee["Location"], let ageStr = employee["Age"], let age = Int(ageStr) { 
      self.name = name 
      self.location = location 
      self.age = age 
     } 
     else { 
      return nil 
     } 
    } 
} 

今すぐあなたのコントローラにEmployeeインスタンスの1つの配列を宣言し、あなたのtableView方法でその配列を使用します。

var employees = [Employee]() 

//Initialize array 
do { 
    let currentData = try Data(contentsOf: currentFileURL!) 
    if let jsonArray = (try? JSONSerialization.jsonObject(with: currentData, options: [])) as? [[String: String]] { 
     self.emplyees = jsonArray.flatMap({ Employee(dictionary: $0) }) 
    } 
    //Reload the tableView 
    self.tableView.reloadData() 

UITableViewメソッドでこの配列を使用するだけです。まず

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "ProductCell") as! CustomTableCell 
    cell.lblName = self.employees[indexPath.row].name 
    //set other details 

    return cell 
} 
0
if let employees = jsonData["employees"] as? [[String:String]] { 
    for employee in employees { 

     if let name = employee["Name"] { 
      // Set employee name 
     } 

     if let location = employee["Location"] { 
      // Set employee location 
     } 

     if let age = employee["Age"] { 
      // Set employee age 
     } 
    } 
} 
0

は、構造体Employee

struct Employee { 
    var title : String 
    var location : String 
    var age : String 
} 

var employees = [Employee]() 

次に、JSONを解析し、データソースのアレイを作成します。

重要:fileURLWithPathURLに設定すると、ファイルシステムのURLにアクセスする際に使用する必要があります。

let currentFileURL = URL(fileURLWithPath: currentFileString) 
do { 
    let currentData = try Data(contentsOf: currentFileURL) 
    let json = try JSONSerialization.jsonObject(with:currentData, options: []) as! [String:Any] 
    let people = json["employees"] as! [[String:String]] 
    for person in people { 
     employees.append(Employee(title: person["Name"]!, location: person["Location"]!, age: person["Age"]!)) 
    }  
} catch let error as NSError { 
    print(error) 
} 

jsonファイルはローカルディスク上にあり、コンテンツの責任を負うので、強制アンラッピングは安全であるか、または設計エラーを示します。

関連する問題