Swift动态键JSON解码报错:预期字典却获字符串/数据问题排查
问题解析:JSON解码错误原因及修正方案
错误核心原因
你碰到的解码错误本质是结构体字段类型与JSON实际数据完全不匹配:
- 拿
UrlsCoins里的website字段来说,JSON里它是纯字符串数组(比如["pthkfb543fm", "49xjybh5mlq"]),但你定义的[CoinWebsites]是自定义对象数组——解码时系统会期望每个数组元素是包含website字段的对象,实际拿到的却是纯字符串,直接触发类型不匹配报错。 - 同理,
twitter、reddit、explorer等字段在JSON中都是字符串数组,你却用了[CoinTwitters]、[CoinReddits]这类自定义结构体数组,同样会导致解码失败。 - 额外问题:你的
CoinsInfo结构体缺失了JSON中存在的status字段,虽然这不是当前报错的直接原因,但要完整解码整个JSON必须补充对应结构。
修正后的结构体定义
把UrlsCoins中的数组类型直接改为[String]?,去掉冗余的自定义结构体,同时补充status相关结构:
// 顶层完整结构体,包含JSON里的status和data struct CoinResponse: Codable { let status: StatusInfo let data: [String: CoinSpecificInfo]? } struct StatusInfo: Codable { let timestamp: String let error_code: Int let error_message: String? let elapsed: Int let credit_count: Int let notice: String? } struct CoinSpecificInfo: Codable { let urls: UrlsCoins? let logo: String? let id: Int? let symbol: String? // 若需要JSON里的其他字段(如name、slug),可自行补充 } struct UrlsCoins: Codable { let website: [String]? let twitter: [String]? let reddit: [String]? let explorer: [String]? // JSON中存在的technical_doc、message_board等字段,按需添加即可 }
解码示例代码
用修正后的结构体执行解码:
do { let decodedResult = try JSONDecoder().decode(CoinResponse.self, from: yourJsonData) print("解码成功,共\(decodedResult.data?.count ?? 0)条货币数据") } catch { print("解码失败:\(error.localizedDescription)") }
内容的提问来源于stack exchange,提问作者Hello422
相关产品推荐
相关产品推荐

