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

Swift解析JSON:如何将嵌套字典键映射为department字段值

问题:如何获取JSON字典键对应的department字段值?

你当前的JSON结构中,resources是一个以部门名称(electronics、mechanical等)为键的字典,但解析时仅提取了字典的值,丢失了作为部门名称的键。以下是解决方法:

解决方案步骤

1. 更新ResourceInfo结构体

添加department字段,用于存储部门名称:

struct ResourceInfo: Decodable {
    let id: String
    let type: String
    let department: String // 新增部门字段
}

2. 修改CustomerInfo的自定义解码逻辑

通过临时结构体解码原始JSON数据,再将字典键作为department赋值给ResourceInfo:

struct CustomerInfo: Decodable {
    let name: String
    let country: String
    let resources: [ResourceInfo]

    enum CodingKeys: CodingKey {
        case name, country, resources
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.name = try container.decode(String.self, forKey: .name)
        self.country = try container.decode(String.self, forKey: .country)
        
        // 临时结构体:匹配JSON中单个resource的结构(仅id和type)
        private struct TempResource: Decodable {
            let id: String
            let type: String
        }
        
        // 解码resources为字典,保留部门名称作为键
        let resourcesDict = try container.decode([String: TempResource].self, forKey: .resources)
        
        // 转换字典为ResourceInfo数组,将键赋值给department字段
        self.resources = resourcesDict.map { departmentName, tempResource in
            ResourceInfo(
                id: tempResource.id,
                type: tempResource.type,
                department: departmentName
            )
        }
    }
}

效果验证

修改后重新解析JSON,dump(result)会输出包含department字段的结果:

Optional(JsonSample.CustomerInfo(name: "John", country: "USA", resources: [
  JsonSample.ResourceInfo(id: "101", type: "PC", department: "electronics"),
  JsonSample.ResourceInfo(id: "201", type: "CAR", department: "mechanical"),
  JsonSample.ResourceInfo(id: "301", type: "CHEM", department: "science")
]))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 18:47:14