You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确解析多维JSON实现带分区的UITableView展示

问题根源

当前Codable解析失败的核心原因是结构体和JSON返回的层级不匹配:接口返回的最外层是带result字段的根对象,result的值才是分区数据数组,你之前直接用单分区结构ReceiveIn解码整个返回数据,层级不匹配自然解析失败。

最优实现方案

直接使用接口返回的Section字段做分区依据,不需要二次遍历分组,实现成本最低。

第一步:调整Codable结构体

补全最外层根结构,你之前定义的单条组件结构体Components是正确的,不需要修改:

// 接口返回最外层根结构
struct RootResponse: Codable {
    let result: [SectionItem]
}

// 单个分区对应的数据结构
struct SectionItem: Codable {
    let Section: String
    let result: [Components]
}

// 单条物料组件条目,原结构无需改动
struct Components: Codable {
    let Owner: String
    let Barcode: String
    let Quantity: String
    let Description: String
    let Status: String
}

第二步:调整数据源变量和解码逻辑

把原来的ReviewList变量类型替换为分区数组类型,再修改解码逻辑:

// 替换原有ReviewList的定义
var ReviewList: [SectionItem] = []

func parse(_ data: Data){
    let decoder = JSONDecoder()
    do {
        // 用根结构解码返回数据
        let response = try decoder.decode(RootResponse.self, from: data)
        ReviewList = response.result
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    } catch {
        // 调试阶段可以打印错误快速定位问题
        print("数据解析错误: \(error)")
    }
}

第三步:适配UITableView数据源方法

解析完成后直接用ReviewList实现数据源协议即可,无需额外分组处理:

func numberOfSections(in tableView: UITableView) -> Int {
    return ReviewList.count
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return ReviewList[section].Section
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return ReviewList[section].result.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MaterialCell", for: indexPath)
    let item = ReviewList[indexPath.section].result[indexPath.row]
    // 按业务需求给Cell赋值即可
    cell.textLabel?.text = item.Description
    cell.detailTextLabel?.text = "条码: \(item.Barcode) 数量: \(item.Quantity) 状态: \(item.Status)"
    return cell
}

不推荐使用Owner字段做分区依据:该方案需要先把所有物料条目拉平成一维数组,再手动按Owner值遍历分组,还要处理字段为空的边界情况,代码量远高于直接使用接口返回的Section结构,没有必要。

内容的提问来源于stack exchange,提问作者Mike Volmar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 15:48:44