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

Swift能否为纯键值对JSON编写无需改源文件的Codable解析逻辑?

动态键JSON的Swift Codable解析方案

完全可以不对原JSON做任何后处理,直接完成Codable解析,无需手动枚举所有键定义模型属性,常用实现方案如下:

方案1:直接解析为字典(最简方案,推荐)

原JSON本质就是键值均为字符串的字典结构,无需自定义Codable结构体,直接用[String: String]类型解析即可,满足查询需求:

import Foundation

// 模拟你的JSON原始数据
let jsonData = """
{
    "peopleA": "nnll",
    "peopleB": "ihyt",
    "peopleC": "udr",
    "peopleD": "vhgd",
    "peopleE": "llll"
}
""".data(using: .utf8)!

do {
    // 直接解析为Swift字典
    let peopleDict = try JSONDecoder().decode([String: String].self, from: jsonData)
    // 输入键名直接查询
    let targetKey = "peopleC"
    if let targetValue = peopleDict[targetKey] {
        print(targetValue) // 输出 udr
    } else {
        print("未找到对应值")
    }
} catch {
    print("解析错误:\(error.localizedDescription)")
}

该方案代码量最小,性能足以应对数千条键值对的解析、查询需求,适合没有其他额外字段需要解析的场景。

方案2:自定义Codable结构体封装

如果后续需要在同个JSON中解析其他固定字段,或者需要对数据做封装管理,可以实现自定义解码逻辑适配动态键:

import Foundation

struct PeopleData: Codable {
    // 存储所有动态键值对
    let allInfo: [String: String]
    
    // 自定义解码逻辑
    init(from decoder: Decoder) throws {
        // 用动态CodingKey遍历所有未知键
        let container = try decoder.container(keyedBy: DynamicCodingKey.self)
        var tempDict = [String: String]()
        for key in container.allKeys {
            tempDict[key.stringValue] = try container.decode(String.self, forKey: key)
        }
        self.allInfo = tempDict
    }
    
    // 动态CodingKey适配任意字符串键
    private struct DynamicCodingKey: CodingKey {
        var stringValue: String
        init?(stringValue: String) {
            self.stringValue = stringValue
            self.intValue = nil
        }
        var intValue: Int?
        init?(intValue: Int) { nil }
    }
}

// 使用示例
do {
    let peopleData = try JSONDecoder().decode(PeopleData.self, from: jsonData)
    let targetValue = peopleData.allInfo["peopleC"] // 取值udr
} catch {
    print(error)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 02:45:05