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

Swift解析API JSON时出现CodingKeys关联失败错误求助

解决JSON解码中keyNotFound("name")的问题

首先,虽然你提供的示例JSON包含name字段,但实际解码时出现找不到该键的错误,大概率是因为传入parseWeatherJSON的data并非你预期的响应内容。以下是具体排查和解决步骤:

1. 确认实际解码的数据内容

在解码前添加代码,将data转换为字符串并打印,检查是否与示例JSON一致:

func parseWeatherJSON(data: Data) {
    // 新增:打印实际接收的JSON字符串
    if let jsonString = String(data: data, encoding: .utf8) {
        print("Received JSON: \(jsonString)")
    }
    
    let decoder = JSONDecoder()
    // ... 原有解码代码
}

如果打印出的JSON没有name字段(比如API返回了错误响应,如请求参数无效时的错误信息),那就是API的问题,需要根据实际响应调整你的模型或请求逻辑。

2. 处理可能缺失的name字段

如果API在某些场景下确实会返回不含name的响应,将WeatherData中的name改为可选类型,避免解码失败:

struct WeatherData: Codable {
    let name: String? // 改为可选类型
    let main: Main
    let weather: [Weather]
}

之后在代码中处理name为nil的情况:

if let name = decodedWeatherData.name {
    let weather = WeatherModel(conditionId: id, temperature: temp, cityName: name)
    print(weather.tempStr)
} else {
    print("City name not available")
}

3. 排除其他潜在问题

  • 检查是否给JSONDecoder设置了自定义的keyDecodingStrategy(比如驼峰转下划线),这会导致键名不匹配。默认的.useDefaultKeys是正确的,无需修改。
  • 确认WeatherData的属性名name没有拼写错误,与JSON中的键完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:13:39