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

Swift JSON解码错误:无法解析fixtures数组数据求助

解决Swift DecodingError: Expected String but found Dictionary的问题

嘿,这个错误我太熟了——本质就是你的Codable模型和API返回的JSON结构不匹配!从报错信息能明确看到问题出在fixtures[0].result这个字段上:你的代码里把它定义成了String类型,但实际API返回的是一个字典,解码器自然就懵了。

快速修复步骤:

  1. 检查你的模型定义
    先找到EventsData结构体里的result属性,大概率你现在的代码是这样的:

    struct EventsData: Codable {
        let result: String // 这里就是问题所在!
        // 其他属性...
    }
    
  2. 创建对应result的字典模型
    根据API返回的result字典结构,定义一个新的Codable结构体。比如如果API返回的result是类似{"homeScore": "3", "awayScore": "1"}这样的格式,就写:

    struct MatchResult: Codable {
        let homeScore: String
        let awayScore: String
        // 这里的字段要和API返回的key完全一致,注意大小写!
    }
    
  3. 修正EventsData的类型
    把EventsData里的result类型改成刚创建的MatchResult:

    struct EventsData: Codable {
        let result: MatchResult // 现在类型匹配了
        // 其他属性...
    }
    

进阶处理:如果result字段可能是字符串或字典

有时候API会搞特殊——比如比赛未开始时result是"-"(字符串),比赛结束后是字典。这种情况可以用自定义枚举来兼容两种类型:

enum MatchResultValue: Codable {
    case placeholder(String)
    case score(MatchResult)
    
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        // 先尝试解码成字符串
        if let placeholder = try? container.decode(String.self) {
            self = .placeholder(placeholder)
        } 
        // 不行就尝试解码成字典模型
        else if let score = try? container.decode(MatchResult.self) {
            self = .score(score)
        } 
        // 都不行就抛出错误
        else {
            throw DecodingError.typeMismatch(
                MatchResultValue.self,
                DecodingError.Context(
                    codingPath: decoder.codingPath,
                    debugDescription: "Expected String or MatchResult dictionary"
                )
            )
        }
    }
    
    // 编码逻辑(如果需要序列化的话)
    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        switch self {
        case .placeholder(let str):
            try container.encode(str)
        case .score(let score):
            try container.encode(score)
        }
    }
}

然后把EventsData里的result改成MatchResultValue类型即可。

最后提醒一句:如果不确定API返回的result具体结构,可以先打印一下原始的JSON数据(比如用print(String(data: yourData, encoding: .utf8))),对照着写模型绝对不会错!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:07:14