You need to enable JavaScript to run this app. Swift JSON解析报错:预期解码数组却得到字典的问题排查修复
优惠活动
大模型
产品
解决方案
定价
更多

Swift JSON解析报错:预期解码数组却得到字典的问题排查修复

触发报错的根本原因
  • 解码目标与JSON根结构不匹配:报错明确提示“预期解码数组却收到字典”,对应代码中decode([Country].self, from: data!)的调用逻辑,是将整个接口响应当数组解析,和实际返回的根结构为单字典的情况完全冲突。
  • 类型引用链路完全断裂:提前定义的Model结构体是匹配接口根字典结构的(包含basepath、items字段),但代码全程未使用该模型,反而引用了未定义的Country类型;变量定义在[Model]和[Country]之间反复切换,没有形成统一的类型对应关系。
  • 表格渲染逻辑存在硬编码阻断:numberOfRowsInSection方法固定返回0,就算解码流程正常,也不会向表格返回任何行数,无法渲染任何单元格内容。
修复步骤

1. 梳理统一的数据类型

删除前后矛盾的错误变量定义,按实际JSON结构拆分独立变量:

// 原错误定义:var dataModel = [Model]() / var dataModel = [Country]()
// 对应接口返回的根字典对象
var rootModel: Model?
// 表格实际展示的数据源,对应Model结构内的items数组
var displayItems = [Item]()

2. 修正解码调用逻辑

替换错误的解码目标,匹配实际的字典根结构:

let decoder = JSONDecoder()
do {
    // 原错误代码:try decoder.decode([Country].self, from: data!)
    let decodedRoot = try decoder.decode(Model.self, from: data!)
    self.rootModel = decodedRoot
    self.displayItems = decodedRoot.items
    DispatchQueue.main.async {
        self.removeSpinner()
        self.tableView.reloadData()
    }
} catch {
    DispatchQueue.main.async {
        print(error)
        self.performRequestError()
    }
}

3. 对接表格数据源逻辑

替换写死返回0的行数计算逻辑,对接正确的展示数据源:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // 原逻辑固定返回0,阻断内容渲染
    return displayItems.count
}

4. 修正单元格赋值逻辑

删除硬编码的"title"占位字符串,从数据源读取实际字段内容填充单元格:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! TableViewCell
    let currentItem = displayItems[indexPath.row]
    cell.updateContent(title: currentItem.title, abstract: currentItem.abstract, thumbnail: currentItem.thumbnail)
    return cell
}

附带问题优化

当前代码中定义的hostingView是未添加到视图层级的空UIView,绑定在该视图上的加载指示器无法正常显示,可将加载指示器的绑定视图直接替换为self.view,避免加载状态不生效的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.30 12:06:07