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

SwiftUI中如何解析包含任意键的JSON数据

SwiftUI中动态键JSON的解析方案

一、基础解析方案:直接转为字典

你的JSON结构是字符串键对应字符串数组,包含固定的"all"键和不确定数量的数字字符串键,最直接的方式是将JSON字符串解析为[String: [String]]类型的字典,操作如下:

1. 解析JSON字符串

import Foundation

// 假设你的JSON字符串变量为jsonString
let jsonString = """
{
  "all": ["foo", "bar", "baz"],
  "4": ["asd", "qwe"],
  "25": ["something", "another"],
  "2": ["xxx", "yyy"]
}
"""

// 解析函数
func parseJSON(_ jsonString: String) -> [String: [String]]? {
    guard let data = jsonString.data(using: .utf8) else { return nil }
    do {
        return try JSONSerialization.jsonObject(with: data, options: []) as? [String: [String]]
    } catch {
        print("解析失败:\(error.localizedDescription)")
        return nil
    }
}

// 调用解析
if let parsedDict = parseJSON(jsonString) {
    // 后续操作写在这里
}

2. 获取"all"对应的列表

直接通过键值访问:

if let allItems = parsedDict["all"] {
    print("all列表内容:\(allItems)")
    // 在SwiftUI中可直接将allItems绑定到List等视图
}

3. 检查特定数字键并获取列表

let targetKey = "123" // 要检查的数字键
if let targetItems = parsedDict[targetKey] {
    print("\(targetKey)对应的列表:\(targetItems)")
} else {
    print("键\(targetKey)不存在")
}

二、Unicode字符处理

Swift的JSON解析会自动处理UTF-8编码的Unicode字符(如åäö),只要你的JSON字符串是标准UTF-8格式,解析后就能直接得到正确的字符,无需额外编码转换。

三、结构化解析方案:使用Codable

如果希望将数据结构化,区分固定的"all"和动态的数字键,可以自定义Codable模型:

struct DynamicJSONData: Codable {
    let all: [String]
    let numericEntries: [String: [String]] // 存储所有数字键对应的数组
    
    // 自定义编码键
    enum FixedCodingKeys: String, CodingKey {
        case all
    }
    
    // 自定义解析逻辑
    init(from decoder: Decoder) throws {
        // 解析固定的"all"键
        let fixedContainer = try decoder.container(keyedBy: FixedCodingKeys.self)
        all = try fixedContainer.decode([String].self, forKey: .all)
        
        // 解析剩余的所有动态键
        let dynamicContainer = try decoder.container(keyedBy: DynamicCodingKey.self)
        numericEntries = [:]
        for key in dynamicContainer.allKeys {
            guard key.stringValue != FixedCodingKeys.all.rawValue else { continue }
            numericEntries[key.stringValue] = try dynamicContainer.decode([String].self, forKey: key)
        }
    }
    
    // 动态编码键实现
    struct DynamicCodingKey: CodingKey {
        var stringValue: String
        init?(stringValue: String) { self.stringValue = stringValue }
        
        var intValue: Int?
        init?(intValue: Int) {
            self.stringValue = String(intValue)
            self.intValue = intValue
        }
    }
}

// 使用Codable解析
func parseWithCodable(_ jsonString: String) -> DynamicJSONData? {
    guard let data = jsonString.data(using: .utf8) else { return nil }
    do {
        return try JSONDecoder().decode(DynamicJSONData.self, from: data)
    } catch {
        print("Codable解析失败:\(error.localizedDescription)")
        return nil
    }
}

// 调用示例
if let dataModel = parseWithCodable(jsonString) {
    print("all列表:\(dataModel.all)")
    print("所有数字键条目:\(dataModel.numericEntries)")
    if let items = dataModel.numericEntries["4"] {
        print("键4的列表:\(items)")
    }
}

方案选择

  • 若仅需快速访问数据,直接使用字典解析更简便;
  • 若需要结构化管理数据(如区分固定键和动态键),推荐使用Codable方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:41:11