使用Swift在UITableView中展示嵌套JSON数组,仅显示name不显示value如何解决
问题根因
- 你代码中写的
if tableView == tableView是恒成立的条件,永远只会走展示name的分支,展示value的分支永远不会被触发,这个判断逻辑完全无效。 - 你声明的
categorydata数组从未被赋值,就算判断逻辑正确,空数组也无法渲染出内容。 - 你当前的数据结构是每个产品对应多个
meta_data的value值,没有明确的逻辑将这些value关联到tableView的渲染流程中。
修复方案
我们以每个cell同时展示产品名称和对应的第一个meta_data的value为例(如果你的需求是其他展示逻辑可以对应调整),修改后的代码如下:
import UIKit // 建议结构体名首字母大写,符合Swift编码规范 struct JsonStruct: Codable { let name: String let meta_data: [Categories] enum CodingKeys: String, CodingKey { case name case meta_data } } struct Categories: Codable { let value: String enum CodingKeys: String, CodingKey { case value } } class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! // 简化数组初始化写法 var arrdata : [JsonStruct] = [] override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self getdata() } func getdata() { // 注意替换为自己的真实key和secret guard let url = URL(string: "https://mywebstaging.net/ab/garnier/wp-json/wc/v3/products?consumer_key=<key>&consumer_secret=<secret>") else { return } URLSession.shared.dataTask(with: url) { [weak self] data, response, error in guard let self = self, error == nil, let data = data else { print("请求出错:\(error?.localizedDescription ?? "未知错误")") return } do{ self.arrdata = try JSONDecoder().decode([JsonStruct].self, from: data) print(self.arrdata) DispatchQueue.main.async { self.tableView.reloadData() } }catch{ print("解析JSON数据出错:\(error.localizedDescription)") } }.resume() } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrdata.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CellTableViewCell let product = arrdata[indexPath.row] cell.lblid.text = product.name // 取第一个meta_data的value赋值,如果需要拼接所有value可以用map+joined处理 cell.lblname.text = product.meta_data.first?.value ?? "无对应数据" return cell } }
如果你需要将所有meta_data的value单独作为行展示,可以先把所有arrdata里的meta_data扁平化合并到一个数组里,再按照对应的数据源逻辑渲染即可。
内容的提问来源于stack exchange,提问作者Ahana Chakraborty
相关产品推荐
相关产品推荐

