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

SwiftUI中如何为根节点含动态Codable键的JSON创建对应struct?

解决方案

方案1:直接用字典类型解码(最简便,无需自定义逻辑)

你遇到的场景本质是接口返回的根节点为键是动态分类名、值是分类结构体的字典,完全不需要额外定义外层的Welcome结构体,直接将响应解码为[String: Category]类型即可。

首先定义依赖的结构体:

// MARK: - 商品模型
struct Product: Codable {
    let title: String
    let id: String
    let url: String
    let details: String
    let duration: String
    let category: String
    let sub_category: String
    let date_added: String
}

// MARK: - 分类模型
struct Category: Codable {
    let products: [Product]
}

解码示例代码:

// jsonData为接口返回的Data类型数据
do {
    let categoryDict = try JSONDecoder().decode([String: Category].self, from: jsonData)
    // 遍历获取所有分类和对应商品
    for (categoryName, categoryInfo) in categoryDict {
        print("分类名:\(categoryName),商品数量:\(categoryInfo.products.count)")
        // 这里写后续业务处理逻辑
    }
} catch {
    print("解码失败:\(error.localizedDescription)")
}

方案2:自定义外层结构体(适用于需要统一封装外层类型的场景)

如果你需要定义统一的外层模型管理所有分类,可以手动实现Codable协议的解码逻辑,适配动态key:

struct Welcome: Codable {
    // 存储所有分类,键为动态分类名
    let allCategories: [String: Category]
    
    // 手动实现解码逻辑
    init(from decoder: Decoder) throws {
        // 定义适配任意字符串key的动态CodingKey
        struct DynamicCodingKey: CodingKey {
            let stringValue: String
            init?(stringValue: String) {
                self.stringValue = stringValue
            }
            let intValue: Int? = nil
            init?(intValue: Int) { nil }
        }
        
        // 获取根节点的所有动态key容器
        let container = try decoder.container(keyedBy: DynamicCodingKey.self)
        var tempCategories = [String: Category]()
        // 遍历所有动态key解码对应分类
        for key in container.allKeys {
            let category = try container.decode(Category.self, forKey: key)
            tempCategories[key.stringValue] = category
        }
        self.allCategories = tempCategories
    }
}

解码示例代码:

do {
    let result = try JSONDecoder().decode(Welcome.self, from: jsonData)
    // 按分类名获取对应商品
    let category1Products = result.allCategories["category1"]?.products
} catch {
    print("解码失败:\(error.localizedDescription)")
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 15:36:04