我的本地磁盘上有一个 .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
}
感谢您的帮助!
保罗
最佳答案
最好的方法是创建自定义 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
}
}
}
现在在您的 Controller 中声明一个 Employee
实例数组,并将该数组与您的 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
}
关于ios - 在 Swift 中从 json 文件读回数据的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41573842/