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

使用Swift Decodable解析JSON遇类型不匹配错误的问题求助

解决Swift Decodable解析JSON时的typeMismatch错误

Hey,这个typeMismatch错误我太熟了——核心问题是你告诉解码器要解析单个字典(对应Currency对象),但Binance的这个API返回的其实是一个字典数组(也就是[Currency]类型)。

先看错误信息里的关键提示:

Expected to decode Dictionary but found an array instead.

你的代码里已经把myDict定义成了[Currency]数组,但大概率在解码步骤中写错了类型,用了Currency.self而不是数组类型,导致解码器预期单个字典,实际拿到数组就报错了。

修正后的完整可运行代码

struct Currency: Decodable {
    let symbol: String
    let price: String
}

// 变量名改成currencyList更贴合语义,毕竟是数组不是字典
var currencyList: [Currency] = []

func testParse() {
    let jsonUrlString = "https://api.binance.com/api/v3/ticker/price"
    guard let url = URL(string: jsonUrlString) else {
        print("Invalid URL")
        return
    }
    
    URLSession.shared.dataTask(with: url) { data, response, error in
        guard let data = data, error == nil else {
            print(error?.localizedDescription ?? "Unknown error occurred")
            return
        }
        
        // 可选:打印返回的JSON字符串,确认结构(调试用)
        if let rawJson = String(data: data, encoding: .utf8) {
            print("Raw JSON response:\n\(rawJson)")
        }
        
        do {
            // 关键修正:解码数组类型 [Currency].self,匹配API返回的数组结构
            currencyList = try JSONDecoder().decode([Currency].self, from: data)
            
            // 验证解析结果
            print("\nSuccessfully parsed \(currencyList.count) currencies")
            if let firstCurrency = currencyList.first {
                print("First currency: \(firstCurrency.symbol) - \(firstCurrency.price)")
            }
        } catch let decodingError {
            print("\nError serialising json: \(decodingError)")
        }
    }.resume()
}

几个关键说明

  • 解码类型匹配:一定要用[Currency].self来解码数组,而不是单个Currency.self——这是解决错误的核心
  • 语义化命名:把myDict改成currencyList,避免自己混淆(它是数组,不是字典)
  • 调试技巧:加一段打印原始JSON的代码,能帮你快速确认API返回的结构,避免类型匹配错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:17:28