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

如何在ViewController中展示嵌套JSON数组元素 解决作者字段赋值报错

错误根因

UILabel的text属性仅接收String类型值,你直接把[String]类型的作者数组赋值给Label,类型不匹配才会抛出该错误。另外你当前代码存在笔误:先后两次给cell.bookAuthor.text赋值,书名title的内容会被后续的作者信息直接覆盖,需要先调整Label赋值的对应关系。

修复方案

你可以任选以下两种常用的数组转字符串的处理方式:

  1. 拼接所有作者名
    适合需要展示全部作者的场景,用joined(separator:)方法将数组元素按指定分隔符拼接为字符串,同时做异常兜底避免空值:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "BookCell",for:indexPath) as! BookCell
    // 修复赋值对应关系:书名赋值给对应Label,可替换为你实际的书名字段属性名
    cell.bookTitle.text = items[indexPath.row].volumeInfo.title
    cell.bookCategory.text = items[indexPath.row].volumeInfo.publisher
    // 作者数组拼接为字符串,多个作者用逗号分隔,无作者时显示“佚名”
    cell.bookAuthor.text = items[indexPath.row].volumeInfo.authors.joined(separator: ", ") ?? "佚名"
    return cell
}
  1. 仅展示首位作者
    适合列表展示空间有限的场景,只取数组第一个元素,多个作者时可追加“等”标识:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "BookCell",for:indexPath) as! BookCell
    cell.bookTitle.text = items[indexPath.row].volumeInfo.title
    cell.bookCategory.text = items[indexPath.row].volumeInfo.publisher
    let authors = items[indexPath.row].volumeInfo.authors
    if !authors.isEmpty {
        cell.bookAuthor.text = authors.count > 1 ? "\(authors.first!) 等" : authors.first
    } else {
        cell.bookAuthor.text = "佚名"
    }
    return cell
}

可选优化建议

部分书籍可能不存在authors字段,建议将VolumeInfo中authors的声明修改为可选数组,避免解析失败:

struct VolumeInfo : Codable {
    let authors : [String]? // 改为可选类型
    let publisher : String?
    let subtitle : String?
    let title : String?
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 12:36:04