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

使用Alamofire上传图片获201状态码但JSON反序列化失败求助

解决Alamofire上传图片后JSON响应序列化失败的问题

你的问题其实很典型:HTTP状态码201确实说明服务器已经成功接收并处理了你的上传请求,但Alamofire的responseJSON方法要求服务器返回的必须是严格符合JSON格式的数据,如果服务器返回的是空内容、纯文本或者格式错误的JSON,就会触发你看到的jsonSerializationFailed错误。

第一步:先搞清楚服务器到底返回了什么

你可以先把responseJSON换成responseString来调试,这样能直接看到服务器返回的原始内容,方便定位问题:

upload.responseString { response in
    print("服务器原始响应内容: \(response.result.value ?? "无响应内容")")
    print("响应状态码: \(response.response?.statusCode ?? 0)")
    
    switch response.result {
    case .failure(let error):
        let message: String
        if let httpStatusCode = response.response?.statusCode {
            print("httpStatusCode: \(httpStatusCode)")
            switch(httpStatusCode) {
            case 404:
                message = "File not found"
            case 500 :
                message = "Internal Error"
            default:
                message = "Connection issue, please make sure you have a good internet access, or please contact IT Support."
            }
        } else {
            message = error.localizedDescription
        }
        completion(message)
    case .success(let content):
        // 这里根据实际返回的内容判断是否成功
        // 比如如果服务器返回"upload success"这类纯文本,就直接调用completion(nil)
        print("上传成功,服务器返回: \(content)")
        completion(nil)
    }
}

第二步:根据实际返回内容调整处理逻辑

运行上面的代码后,你会看到服务器返回的真实内容:

  • 如果返回的是类似{"code":200,"message":"success"}的有效JSON,那可能是你之前的JSON解析逻辑有问题(不过这种情况很少见,因为错误提示是字符1就无效);
  • 更可能的情况是服务器返回的是纯文本(比如"upload completed")或者空响应,这时候你就不需要用responseJSON,直接用responseString或者responseData来处理即可。

为什么201状态码还会报错?

HTTP状态码只表示请求的处理结果,和响应内容的格式无关。201的含义是"请求已成功,并且创建了新的资源",但服务器完全可以返回非JSON格式的内容来告知结果,这时候responseJSON就会因为无法解析非JSON内容而抛出错误。

总结

要么让后端调整返回格式,确保返回有效的JSON;要么在客户端这边根据服务器实际返回的内容,改用对应的响应处理方法(比如responseString)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:58:10