【问题标题】:What is the proper approach to read back data from a json file in Swift?在 Swift 中从 json 文件中读取数据的正确方法是什么?
【发布时间】:2017-01-10 16:40:51
【问题描述】:

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

感谢您的帮助!

保罗

【问题讨论】:

    标签: ios json swift3


    【解决方案1】:

    最好的方法是创建自定义 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
            }
        }
    }
    

    现在在您的控制器中声明一个 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
    }
    

    【讨论】:

      【解决方案2】:
      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
              }
          }
      }
      

      【讨论】:

        【解决方案3】:

        首先创建一个结构体Employee和一个数据源数组

        struct Employee {
            var title : String
            var location : String
            var age : String
        }
        
        var employees = [Employee]()
        

        然后解析 JSON。

        重要提示:在访问文件系统 URL 时,您必须在 URL 上使用 fileURLWithPath

        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 文件位于本地磁盘上,并且您对内容负责,因此强制解包是安全的或显示设计错误。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-10
          • 2011-03-13
          • 2020-08-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多