ios - 在 Swift 中从 json 文件读回数据的正确方法是什么?

标签 ios json swift3

我的本​​地磁盘上有一个 .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
            } 

感谢您的帮助!

保罗

最佳答案

最好的方法是创建自定义 classstruct 并在 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/

相关文章:

json - 我正面临这个错误 A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution

ios - 使用 MKGeodesicPolyline Swift 3 计算距离将出现错误

swift - 是否可以创建一个模仿 CKRecord 的类?

ios - 在 iOS 设备上运行 SUP101 时出现异常

java - Faunus json 读取器在 json 文件格式中出现错误

javascript - TOMCAT报告此错误: INFO: Character decoding failed

ios - SWRevealViewController 不与 swift 3 切换

objective-c - 如何在 iOS 上启用新的 Objective-C 对象文字?

ios - Firebase - 构建数据库的正确方法

ios - removeFromSuperView 不适用于按钮