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

Swift Codable技术实现:如何从嵌套数据生成多个对象

使用Swift Codable解析嵌套JSON结构

没问题,我来一步步帮你搞定这个嵌套结构的解析。其实Codable就是为这种多层嵌套的数据设计的,只要把每个层级的数据都对应成Swift结构体,就能轻松解析出所有对象。

第一步:定义对应Codable模型

根据你给出的JSON结构,我们需要从最底层的Reference开始,逐层往上定义遵循Codable协议的结构体:

// 最底层的引用信息模型
struct Reference: Codable {
    let id: String
    let origin: String
}

// 球队模型
struct Team: Codable {
    let alias: String
    let id: String
    let market: String
    let name: String
    let references: [Reference]
}

// 分区模型
struct Division: Codable {
    let alias: String
    let id: String
    let name: String
    let teams: [Team]
}

// 联盟模型
struct Conference: Codable {
    let alias: String
    let divisions: [Division]
}

// 根响应模型:因为你的JSON根是一个字典,key为"conferences",对应联盟数组
struct RootResponse: Codable {
    let conferences: [Conference]
}

这里要注意:你的原始JSON根结构是一个包含conferences键的字典,不是直接的联盟数组,所以必须定义RootResponse来包裹,不然直接解析[Conference].self会抛出解码错误。

第二步:解析JSON数据

假设你已经拿到了JSON对应的Data类型数据(比如从网络请求返回、本地文件读取),接下来用JSONDecoder进行解码:

// 示例:假设jsonData是你获取到的JSON数据
do {
    let decoder = JSONDecoder()
    // 解码根响应
    let rootResponse = try decoder.decode(RootResponse.self, from: jsonData)
    
    // 现在你可以拿到所有联盟、分区、球队对象了
    let allConferences = rootResponse.conferences
    
    // 遍历打印验证(实际使用按需处理)
    for conference in allConferences {
        print("联盟:\(conference.alias)")
        for division in conference.divisions {
            print("  分区:\(division.name)")
            for team in division.teams {
                print("    球队:\(team.name)(\(team.market)),ID:\(team.id)")
            }
        }
    }
} catch {
    print("解码失败:\(error.localizedDescription)")
    // 这里可以根据具体错误类型做处理,比如类型不匹配、字段缺失等
}

一些实用注意事项

  • 字段不匹配处理:如果JSON中的键名和Swift属性名不一致(比如JSON里是team_id,Swift里想叫teamId),可以在结构体里定义CodingKeys枚举来映射:
    struct Team: Codable {
        let alias: String
        let teamId: String
        // 其他属性...
        
        enum CodingKeys: String, CodingKey {
            case alias
            case teamId = "id" // 比如如果JSON里的key是"id",Swift里叫teamId
            // 其他映射...
        }
    }
    
  • 可选字段处理:如果某些字段可能不存在(比如部分球队没有references),可以把属性定义为可选类型:let references: [Reference]?
  • 自定义解码逻辑:如果有特殊的解码需求(比如日期格式、数字转字符串),可以自定义init(from decoder: Decoder)方法来实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:38:19