如何在ViewController中展示嵌套JSON数组元素 解决作者字段赋值报错
错误根因
UILabel的text属性仅接收String类型值,你直接把[String]类型的作者数组赋值给Label,类型不匹配才会抛出该错误。另外你当前代码存在笔误:先后两次给cell.bookAuthor.text赋值,书名title的内容会被后续的作者信息直接覆盖,需要先调整Label赋值的对应关系。
修复方案
你可以任选以下两种常用的数组转字符串的处理方式:
- 拼接所有作者名
适合需要展示全部作者的场景,用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 }
- 仅展示首位作者
适合列表展示空间有限的场景,只取数组第一个元素,多个作者时可追加“等”标识:
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
相关产品推荐
相关产品推荐

