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

iOS Swift中如何过滤动态JSON并提取Object类型下contentType与URL值

解决方案

你原有代码存在两个核心问题:一是筛选逻辑错误,且type字段匹配时没有和JSON实际值的大小写对齐(JSON里是Object,你写的是小写object);二是做了冗余的字典转字符串再转回JSON的操作,既浪费性能又容易触发不必要的转换错误。

核心实现逻辑

  • 先将接口返回的成功数据转换为和JSON结构匹配的[String: [String: Any]]格式
  • 遍历所有顶层节点,筛选出type字段值为Object的节点
  • 对筛选出的节点,校验value字段为字典结构,且同时包含contentType和url两个字符串类型的属性
  • 提取符合条件的属性值存储使用

修正后的完整代码

AF.request(v, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers).responseJSON { (response: AFDataResponse<Any>) in
    print("process instance id api document view list::::", response.result)
    
    switch response.result {
    case .success(let value):
        self.view.removeLoading()
        // 存储最终提取结果,可根据自己的需求修改存储结构
        var extractedList = [(contentType: String, url: String)]()
        
        // 校验顶层JSON结构是否符合预期
        guard let rootDict = value as? [String: [String: Any]] else {
            print("返回JSON结构和预期不匹配")
            return
        }
        
        // 遍历筛选符合要求的节点
        for (_, nodeInfo) in rootDict {
            // 筛选type为Object的节点,注意大小写和JSON里的取值完全一致
            guard let nodeType = nodeInfo["type"] as? String, nodeType == "Object" else {
                continue
            }
            // 校验value字段包含需要的两个属性
            guard let valueDict = nodeInfo["value"] as? [String: Any],
                  let contentType = valueDict["contentType"] as? String,
                  let url = valueDict["url"] as? String else {
                continue
            }
            // 这里额外处理了你示例里contentType末尾的空格,不需要可以删掉trim操作
            let cleanContentType = contentType.trimmingCharacters(in: .whitespacesAndNewlines)
            extractedList.append((cleanContentType, url))
        }
        
        // 验证输出结果
        print("提取到的有效资源数量:\(extractedList.count)")
        for item in extractedList {
            print("contentType: \(item.contentType), url: \(item.url)")
        }
        
    case .failure(let error):
        self.view.removeLoading()
        print("请求错误:", error)
    }
}

额外说明

如果你的JSON结构可能存在嵌套的Object类型节点,只需要在上面的遍历逻辑里加上递归判断即可,当前代码适配你给出的示例JSON的单层结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:54:05