【问题标题】:Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(错误域=NSCocoaErrorDomain 代码=3840
【发布时间】:2018-04-08 19:41:33
【问题描述】:

我正在开发 swift 项目并使用 Alamofire 调用 web 服务。 但是,在调用 post 方法时,我收到以下错误。

Header file :

let accessTokenHeaderFile = [
    "Accept": "application/json",
    "Content-Type" :"application/json",
    "X-TOKEN" : UtilityClass.sharedInstance.accessTokenString
]

        Alamofire.request(urlString, method: .post, parameters: params as? [String:Any], encoding: JSONEncoding.default, headers: accessTokenHeaderFile).responseJSON { response in
          requestVC.removeLoader()
            switch (response.result) {
            case .success:
                if response.result.value != nil{
                    completionHandler (response.result.value)
                }
                break
            case .failure(let error):
                failureHandler (error as NSError?)
                break
            }
        }

错误是

FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))

任何人都可以建议我,如何解决这个问题,我尝试使用谷歌搜索,但无论我找到什么答案都对我没有帮助。

【问题讨论】:

  • 响应似乎不是有效的 JSON。您能否尝试获取 responseString 而不是 responseJSON 并检查其 JSON 有效性?
  • 我是 swift 新手,能否请您指导我如何从 responseJSON 更改为 responseString?
  • 你可以尝试打印返回值并检查JSON语法是否正确吗?

标签: ios iphone swift xcode alamofire


【解决方案1】:

错误 3840 表示来自服务器的响应不是有效的 JSON 字符串。 所以你可以检查你的 parameters key value 可能是分配错误,因为 类似于 responseString 而不是 responseJSON.

【讨论】:

  • 我明白,但我该如何分配/执行呢?
  • 你的响应字典键和api键是否匹配?
  • 请将您的响应字典键与 api 键相同。错误自动解决。
【解决方案2】:

您的响应不是有效的 json,因此您收到此错误。请检查response.response?.statusCode 以查看服务器返回的内容。如果您想查看实际响应,请尝试使用responseStringresponseData 方法而不是responseJSON

例如

Alamofire.request(urlString, method: .post, parameters: params as? [String:Any], encoding: JSONEncoding.default, headers: accessTokenHeaderFile). responseData {

您可以了解更多response methods here

【讨论】:

  • 无法将“Foundation._NSSwiftData”(0x1114f1990)类型的值转换为“NSDictionary”(0x10bdde2d8)。收到此错误
  • 在打印错误代码时,(lldb) po response.response?.statusCode ▿ 可选 - some : 404
  • 需要将数据转换成json字典,可以直接强制转换
猜你喜欢
  • 2017-06-16
  • 2015-03-11
  • 2020-03-14
  • 2016-02-26
  • 1970-01-01
  • 2016-07-10
  • 1970-01-01
  • 1970-01-01
  • 2014-11-02
相关资源
最近更新 更多