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

如何将GET请求返回的JSON响应作为参数传入后续POST API调用

问题解决方法

你遇到的核心问题有2个:

  1. 对Pixlab的facedetect接口返回结构解析错误,该接口返回的不是直接的人脸数组,而是外层包裹了状态、人脸列表等字段的对象,直接解码[Face].self必然失败
  2. 传参时做了不必要的类型转换(转字符串等),反而导致格式不符合接口要求

具体修复步骤

1. 定义符合接口规范的Codable结构体

首先根据facedetect接口的返回结构定义对应的数据模型:

// 单个人脸坐标结构
struct Face: Codable {
    let left: Int
    let top: Int
    let width: Int
    let height: Int
    // 可根据接口返回的其他字段自行补充
}

// facedetect接口完整响应结构
struct FaceDetectResponse: Codable {
    let faces: [Face]
    let status: Int
    let error: String?
    // 可根据接口返回的其他字段自行补充
}

2. 修改GET请求的解析逻辑

修正解析逻辑,不要使用强制解包的try!,避免崩溃同时方便排查错误:

//MARK: - PIXLAB facedetect
func facedetectGET(uploadedUrl: String) {
    var urlComponents = URLComponents(string: "https://api.pixlab.io/facedetect")
    urlComponents?.queryItems = [
        URLQueryItem(name: "img", value: uploadedUrl),
        URLQueryItem(name: "key", value: Constants.pixlabAPIkey),
    ]
    guard let url = urlComponents?.url else { return }
    
    var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10.0)
    request.httpMethod = "GET"
    request.addValue("Bearer \(Constants.pixlabAPIkey)", forHTTPHeaderField: "Authorization")
    
    let session = URLSession.shared
    let dataTask = session.dataTask(with: request) { (data, response, error) in
        guard let data = data, error == nil else {
            print(error ?? "请求失败")
            return
        }
        do {
            // 解析完整的响应结构
            let detectResponse = try JSONDecoder().decode(FaceDetectResponse.self, from: data)
            guard detectResponse.status == 200 else {
                print("人脸检测失败:\(detectResponse.error ?? "未知错误")")
                return
            }
            print("SUCCESS: 检测到\(detectResponse.faces.count)张人脸")
            // 直接传递解析好的人脸数组即可,不需要转字符串
            mogrify(uploadedUrl: uploadedUrl, cords: detectResponse.faces)
        } catch {
            print("解析失败:\(error)")
        }
    }
    dataTask.resume()
}

3. 修改POST请求的传参逻辑

把cord参数的类型从Any改为明确的[Face],避免类型不匹配导致序列化错误:

//MOGRIFY CALL
func mogrify(uploadedUrl: String, cords: [Face]) {
    let mogrifyurl = URL(string: "https://api.pixlab.io/mogrify")!
    // 直接传入解析好的人脸数组即可
    let param: [String: Any] = [
        "img": uploadedUrl,
        "cord": cords,
        "key": Constants.pixlabAPIkey // 部分接口要求body里也要传key,可根据文档补充
    ]
    
    var request = URLRequest(url: mogrifyurl)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("Bearer \(Constants.pixlabAPIkey)", forHTTPHeaderField: "Authorization")
    request.httpMethod = "POST"
    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: param, options: [])
    } catch {
        print("参数序列化失败:\(error)")
        return
    }

    URLSession.shared.dataTask(with: request) { (data, response, error) in
        if let error = error {
            print("请求失败:\(error)")
            return
        }
        guard let data = data else {
            print("无返回数据")
            return
        }
        do {
            let json = try JSONSerialization.jsonObject(with: data)
            print("mogrify返回:\(json)")
        } catch {
            print("返回解析失败:\(error)")
        }
    }.resume()
}

额外注意事项

  • 所有强制解包、强制try的逻辑都替换为可选绑定和错误捕获,方便定位具体的错误节点
  • 不需要将人脸数据转成字符串再传参,正确解析后的[Face]结构体可以被JSONSerialization正确序列化为符合要求的数组格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:06:04