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

Cocoa应用中Alamofire 4 PUT请求移除JSON字符串反斜杠

解决Alamofire 4 PUT请求中JSON反斜杠问题

嘿,我一眼就看出问题所在啦!你遇到的JSON字符串带反斜杠的情况,是因为重复编码JSON导致的——你先手动用JSONEncoder把ResponseMessage转成了JSON数据,紧接着又调用JSONEncoding.default.encode(request),这相当于把已经是JSON格式的httpBody又当成普通字符串转义了一遍,自然就多出了反斜杠。

修正后的代码

直接移除JSONEncoding的调用,同时手动设置请求的Content-Type头,告诉服务器这是JSON格式的请求体就好:

func putData(responseMessage: ResponseMessage) {
    guard let url = URL(string: "\(responseMessage.uri)?overwrite=true") else {
        // 处理URL无效的情况
        print("Invalid URL")
        return
    }
    
    var request = URLRequest(url: url)
    request.httpMethod = HTTPMethod.put.rawValue
    // 手动设置Content-Type为application/json
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    
    do {
        // 只做一次JSON编码
        let data = try JSONEncoder().encode(responseMessage)
        request.httpBody = data
        
        Alamofire.request(request)
            .validate() // 保持你的验证逻辑
            .responseJSON { response in
                // 处理响应结果
                switch response.result {
                case .success(let value):
                    print("Success: \(value)")
                case .failure(let error):
                    print("Error: \(error)")
                }
            }
    } catch {
        print("Encoding error: \(error)")
    }
}

关键说明

  • 去掉JSONEncoding.default.encode(request)这一步:这个方法是用来把普通参数(比如字典)编码成JSON的,而你已经手动完成了编码,不需要再让Alamofire处理一遍。
  • 手动添加Content-Type头:因为你自己构建了JSON请求体,需要明确告诉服务器请求的格式,否则服务器可能无法正确解析。

这样修改后,发送的JSON就不会有多余的反斜杠啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:31:01