【问题标题】:Parse JSON array with Swiftyjson in Swift 2.3在 Swift 2.3 中使用 Swiftyjson 解析 JSON 数组
【发布时间】:2017-05-08 08:44:46
【问题描述】:

我在 Swift 2.3 中使用 Swiftyjson。在得到以下 json 响应之前,我已经能够毫无问题地将 json 数组解析为 UITableview:

{
  "CAR": [
    {
      "SID": "1",
      "NAME": "BMW",
    },
    {
      "SID": "2",
      "NAME": "MERCEDES",
    },
],
  "BIKE": [
    {
      "SID": "3",
      "NAME": "KAWASAKI",
    },
    {
      "SID": "4",
      "NAME": "HONDA",
    },
 ]
}

问题如何将“CAR”和“BIKE”解析为 tableview 部分并将它们的项目放在每个部分下?我设法使用以下方法获取“密钥”:

// Other Code 
let json = JSON(data)
for (key, subJson) in json {
    self.array.append(key)
}

print(self.array)
["CAR", "BIKE"]

我想知道如何遍历每个部分并正确获取它们的项目。任何帮助都会很棒!

【问题讨论】:

标签: ios json swift uitableview swifty-json


【解决方案1】:

由于您没有显示您从哪里获取 json 数据,我已经通过将您的 JSON 放在 .json 文件中进行了测试。此外,这不使用 SwiftyJSON,但您将能够修改语法以获得相同的结果。

class TableViewController: UITableViewController {

    var tableData = Dictionary<String,Array<Dictionary<String,String>>>()

    var sections = Array<String>()

    override func viewDidLoad() {
        super.viewDidLoad()

        load(file: "document")
    }

    func load(file:String) {

        guard let path = Bundle.main.path(forResource: file, ofType: "json") else { return }

        guard let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else { return }

        guard let json = try? JSONSerialization.jsonObject(with: data) else { return }

        guard let dict = json as? Dictionary<String,Array<Dictionary<String,String>>> else { return }

        self.tableData = dict

        self.sections = dict.keys.sorted()

        self.tableView.reloadData()
    }

    // MARK: - Table view data source

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

        return self.sections.count
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

        let key = self.section[section]

        return key
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        let key = self.section[indexPath.section]

        return self.tableData[key]?.count ?? 0
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        // Configure the cell...

        let key = self.section[indexPath.section]

        let cellData = self.tableData[key]?[indexPath.row]

        cell.textLabel?.text = cellData?["NAME"]

        cell.detailTextLabel?.text = "SID: \(cellData?["SID"] ?? "Unknown")"

        return cell
    }
}

这是它在 iPhone 上的样子。

【讨论】:

  • 您对 JSON 选项 @vadian 的看法是正确的。关于表格数据,由于数据很少,我这样做只是为了了解如何进行表格视图。我已经修改了代码,使其有一个单独的数组来存储这些部分,这样 tableData.keys 就不会一直被调用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多