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

Swift中如何解码顶层含未知键的JSON?解码失败求助

Swift解码含动态顶层键的JSON问题解决

问题原因

你当前的Test结构体定义了content属性,但目标JSON的顶层并没有content这个键,而是直接由多个任意名称的动态键(如unknown_key1、unknown_key2)组成的键值对。JSON解码器找不到与content对应的字段,因此解码失败。

解决方案

方案1:直接解码为字典类型(最简洁)

不需要Test结构体,直接将JSON解码成[String: Content]类型:

do {
    let decodedData = try JSONDecoder().decode([String: Content].self, from: data)
    // decodedData 就是包含动态键的字典,键为JSON中的顶层键,值为Content实例
} catch {
    print("解码失败:\(error)")
}

Content结构体保持原定义即可:

struct Content: Decodable {
    let info: String
    let text: String
}

方案2:封装为自定义结构体(如需额外封装)

如果需要将结果封装在Test结构体中,可通过自定义Decodable实现处理动态键:

struct Test: Decodable {
    let content: [String: Content]
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: DynamicCodingKey.self)
        var contentDict = [String: Content]()
        
        // 遍历所有顶层动态键,解码为Content实例
        for key in container.allKeys {
            let contentValue = try container.decode(Content.self, forKey: key)
            contentDict[key.stringValue] = contentValue
        }
        
        self.content = contentDict
    }
    
    // 自定义动态CodingKey,用于匹配任意字符串键
    private struct DynamicCodingKey: CodingKey {
        let stringValue: String
        init?(stringValue: String) {
            self.stringValue = stringValue
        }
        
        let intValue: Int?
        init?(intValue: Int) {
            self.intValue = intValue
            self.stringValue = String(intValue)
        }
    }
}

struct Content: Decodable {
    let info: String
    let text: String
}

之后即可正常使用JSONDecoder().decode(Test.self, from: data)完成解码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 07:15:34