Swift 解析 JSON 获取 URL 内容

您想要从 JSON 中提取 URL 内容,可以使用以下 Swift 代码:

if let jsonString = '{
    "code": 200,
    "success": true,
    "data": {
        "url": "https://lyt.longyou.gov.cn:30443/srv/qrcode/code/scan?tk=7d4eb6e351094d63bc0baa943991d47b"
    },
    "msg": "操作成功"
}'.data(using: .utf8) {
    do {
        if let json = try JSONSerialization.jsonObject(with: jsonString, options: []) as? [String: Any],
           let data = json["data"] as? [String: Any],
           let url = data["url"] as? String {
            print(url) // 打印url值
        }
    } catch {
        print(error.localizedDescription)
    }
}

代码解析:

  1. 将 JSON 字符串转换为 Data 对象。
  2. 使用 JSONSerialization 将 Data 对象解析为字典。
  3. 访问字典中的 "data" 字段,并获取其中的 "url" 值。
  4. 打印 URL 值。

注意: 这段代码假设 JSON 结构与示例一致。如果您的 JSON 结构不同,请根据实际情况修改代码。

了解更多:

Swift 解析 JSON 获取 URL 内容

原文地址: https://www.cveoy.top/t/topic/naMM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录