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

如何在Swift中解析TMDB API返回的非数组格式剧集数据?

解析TMDB API动态季数结构为数组(Swift实现)

我通过TMDB API获取电视剧集数据时,返回的JSON并非数组形式,而是以season/1、season/2这类字符串作为键的对象结构。需要实现无需预先指定季数,就能将所有季数据转换为数组的解析逻辑。

原问题代码(无法适配任意季数)

struct Result: Codable {
    var season1: Season?
    var season2: Season?
    var id: Int?

    enum CodingKeys: String, CodingKey {
        case season1
        case season2
        case id
    }
}

struct Season: Codable {
    var id: Int?

    enum CodingKeys: String, CodingKey {
        case id
    }
}

返回的JSON示例

{
"id" : 1234,
"season/1": {
  "id": 1234
   },
"season/2": {
  "id": 12345
   }
}

解决方案:动态编码键实现灵活解析

通过自定义**动态编码键(Dynamic Coding Key)**可以遍历所有键并筛选季相关字段,将其统一转换为数组。完整实现代码如下:

struct Season: Codable {
    var id: Int?
    
    enum CodingKeys: String, CodingKey {
        case id
    }
}

struct ShowResult: Codable {
    var id: Int?
    var seasons: [Season]
    
    // 自定义动态编码键,支持任意字符串键解析
    private struct DynamicCodingKeys: CodingKey {
        var stringValue: String
        init?(stringValue: String) {
            self.stringValue = stringValue
        }
        
        var intValue: Int?
        init?(intValue: Int) {
            return nil
        }
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: DynamicCodingKeys.self)
        
        var seasonsArray = [Season]()
        var showId: Int?
        
        for key in container.allKeys {
            if key.stringValue.contains("season/") {
                // 解码季数据并加入数组
                let season = try container.decode(Season.self, forKey: key)
                seasonsArray.append(season)
            } else if key.stringValue == "id" {
                // 单独处理剧集ID字段
                showId = try container.decode(Int.self, forKey: key)
            }
        }
        
        self.id = showId
        self.seasons = seasonsArray
    }
}

代码说明

  • DynamicCodingKeys实现CodingKey协议,让解码器能处理任意字符串格式的键
  • 在自定义的init(from:)方法中遍历所有键:
    • 筛选包含season/的键,解码为Season对象后存入数组
    • 单独提取id字段,保留剧集的基础标识信息
  • 最终所有季数据都会被收集到seasons数组中,无需预先固定季数,适配任意数量的剧集季

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 05:45:20