简体   繁体   English

如何将JSON解析为Swift中的tableView?

[英]How to parse JSON to the tableView in Swift?

Please give me advise, I can not figure out how to parse data in a table view properly.请给我建议,我无法弄清楚如何正确解析表格视图中的数据。

在此处输入图像描述

Here is my model:这是我的 model:

struct ContinentRoot: Codable {
let links: ContinentMiddle 
}

struct ContinentMiddle: Codable {
let continentItems: [ContinentsResponse]
}

struct ContinentsResponse: Codable {
let name: String
let href: String
}

In ViewController I add tableView, continentsArray ([ContinentRoot]) and do some regular things for networking.在 ViewController 中,我添加了 tableView、continentsArray ([ContinentRoot]) 并为网络做一些常规的事情。 I guess that the problem may be here, because in the networking method everything seems normal:我想问题可能出在这里,因为在网络方法中一切似乎都很正常:

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ContinentsTableViewController", for: indexPath)
    let model = continentsArray[indexPath.row].links.continentItems[indexPath.row].name
    cell.textLabel?.text = model
    return cell
}

Thank you so much for for attention!非常感谢您的关注!

According to your attachment design:根据您的附件设计:

if continentsArray is an array of "ContinentRoot" s.如果continentsArray"ContinentRoot"的数组。 and you want to show the links in the selected ContinentRoot you must first select it, and use it like below:并且您想在所选 ContinentRoot 中显示链接,您必须首先 select 它,然后像下面这样使用它:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return selectedContinent.links.continentItems.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ContinentsTableViewController", for: indexPath)
    let model = selectedContinent.links.continentItems[indexPath.row].name
    cell.textLabel?.text = model
    return cell
}  

if Not you must use your code and change this line:如果不是,您必须使用您的代码并更改此行:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ContinentsTableViewController", for: indexPath)
    
let selectedIndex = .zero // or every index you want
    let model = continentsArray[indexPath.row].links.continentItems[selectedIndex].name
    cell.textLabel?.text = model
    return cell
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM