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

Swift 5嵌套JSON解析结构体构建问题:basicInformation字段解析返回nil求助

问题排查与解决:嵌套JSON解析中year返回nil的原因

你的问题很典型——JSON字段名和Swift结构体属性名不匹配,且未建立正确的映射关系,导致basicInformation解码失败为nil,进而访问year时返回nil。

具体原因

查看你的JSON数据,嵌套对象的键是basic_information(蛇形命名),但MyReleases结构体里对应的属性是basicInformation(驼峰命名)。Swift的Codable默认会严格匹配字段名,不会自动转换蛇形与驼峰格式,所以解码器找不到basicInformation对应的JSON键,最终把这个属性解码为nil。

解决方案

你有两种可选的修复方式,可根据场景灵活选择:

方法1:给MyReleases添加CodingKeys映射

这种方式适合仅少数字段需要映射的场景,能明确指定每个属性对应的JSON键:

struct MyReleases: Codable {
    var date_added: String
    let basicInformation: BasicInformation?
    
    // 添加CodingKeys,建立属性与JSON键的映射
    enum CodingKeys: String, CodingKey {
        case date_added
        case basicInformation = "basic_information"
    }
}

方法2:配置JSONDecoder自动转换蛇形命名

如果你的JSON里有大量蛇形命名的字段,建议直接给解码器设置keyDecodingStrategy,自动将蛇形键转换为驼峰属性名:

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase

// 用配置好的解码器解析JSON
do {
    let json = try decoder.decode(Response.self, from: jsonData)
    print(json.releases[3].basicInformation?.year) // 现在能正确输出year值
} catch {
    print("解码失败:\(error)")
}

验证效果

两种方法都能让basicInformation完成正确解码,之后再访问json.releases[3].basicInformation?.year就能拿到对应的year数值了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 16:32:38