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

Swift 4中如何处理嵌套JSON?自定义项目Codable结构体构建疑问

搞定嵌套JSON的Codable结构体实现

嘿,我明白你现在的困扰——处理这种多字段混合的JSON时,确实容易搞不清怎么对应Codable结构体。先把你给出的JSON片段补全并整理一下(看字段风格应该是彩票开奖类的数据):

{
  "acumulado": "sim",
  "cidades": [],
  "data": "2018-05-02",
  "ganhadores": [0, 91, 6675],
  "numero": 2036,
  "proximo_data": "2018-05-05",
  "proximo_estimativa": 22000000,
  "rateio": [0, 21948.81, 427.46],
  "sorteio": [7, 8, 19, 23, 27, 58],
  "valor_acumulado": 0.0
}

接下来直接给你对应的Swift Codable结构体实现,我会加一些实用的解析技巧,方便你直接复用:

import Foundation

// 主结构体,对应整个JSON响应
struct LotteryDraw: Codable {
    let acumulado: String
    let cidades: [String] // 如果后续cidades数组里是带详情的字典,可改成自定义结构体数组,比如[City]
    let data: Date
    let ganhadores: [Int]
    let numero: Int
    let proximoData: Date
    let proximoEstimativa: Int
    let rateio: [Double]
    let sorteio: [Int]
    let valorAcumulado: Double
    
    // 手动映射JSON蛇形命名到Swift驼峰命名
    enum CodingKeys: String, CodingKey {
        case acumulado, cidades, data, ganhadores, numero
        case proximoData = "proximo_data"
        case proximoEstimativa = "proximo_estimativa"
        case rateio, sorteio
        case valorAcumulado = "valor_acumulado"
    }
}

// 解析示例:假设你已从URL获取到data数据
func parseLotteryData(from data: Data) throws -> LotteryDraw {
    let decoder = JSONDecoder()
    // 处理日期格式:匹配JSON里的"yyyy-MM-dd"格式
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    dateFormatter.locale = Locale(identifier: "pt_BR") // 适配JSON里的葡萄牙语字段,避免解析异常
    decoder.dateDecodingStrategy = .formatted(dateFormatter)
    
    // 偷懒小技巧:不想写CodingKeys的话,开启自动蛇形转驼峰
    // decoder.keyDecodingStrategy = .convertFromSnakeCase
    
    return try decoder.decode(LotteryDraw.self, from: data)
}

关键细节说明:

  • 字段映射:我用CodingKeys手动处理了JSON和Swift的命名差异,如果你觉得麻烦,直接开启decoder.keyDecodingStrategy = .convertFromSnakeCase就能自动完成蛇形到驼峰的转换,不用写枚举。
  • 日期处理:JSON里的日期是字符串格式,必须给解码器配置对应格式的DateFormatter,否则会解析失败;设置葡萄牙语locale是因为JSON里出现了"sim"这类葡语词汇,能避免 locale 导致的解析问题。
  • 数组类型适配:目前cidades是空数组,我默认按字符串数组定义;如果后续这个数组里是包含城市信息的字典,你只需要新建一个struct City: Codable,把cidades的类型改成[City]即可。
  • 数值类型匹配:rateio是带小数的数值,所以用[Double];proximo_estimativa是整数,用Int,必须严格和JSON字段类型对应,不然解析会报错。

这样写出来的结构体就能完美解析你给出的JSON响应了,你可以根据实际完整的JSON字段再微调细节~

内容的提问来源于stack exchange,提问作者Nickolas de Luca Alberton

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:12:30