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

Swift中如何从JSON响应提取web href字段并赋值给变量

提取JSON响应中的web href字段

方法一:使用JSONSerialization字典解析

直接在现有代码基础上修改解析逻辑,逐层转换类型提取目标字段:

do {
    // 将JSON数据转为字典类型
    guard let responseDict = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
        print("无法解析为字典")
        semaphore.signal()
        return
    }
    // 提取web子字典,再获取href字段
    if let webDict = responseDict["web"] as? [String: String], let targetURL = webDict["href"] {
        print("提取到的URL:\(targetURL)")
        // 可将targetURL赋值给自定义变量使用,比如:
        // let myTargetURL = targetURL
    }
} catch {
    print(error)
}

方法二:使用Codable模型解析(推荐)

这种方式类型安全、可读性更强,适合复杂JSON结构的场景:

  1. 定义与JSON结构匹配的Codable模型:
struct APIResponse: Codable {
    let account: Account
    let sdk: SDK
    let timestamp: String
    let web: Web
}

struct Account: Codable {
    let id: String
}

struct SDK: Codable {
    let token: String
}

struct Web: Codable {
    let href: String
}
  1. 替换原有解析代码:
do {
    let decoder = JSONDecoder()
    let apiResponse = try decoder.decode(APIResponse.self, from: data)
    let targetURL = apiResponse.web.href
    print("提取到的URL:\(targetURL)")
    // 直接使用targetURL变量即可
} catch {
    print(error)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 03:50:24