Alamofire使用报错:jsonObject调用无匹配及Decodable适配问题
Alamofire网络请求切换中的错误解决方法
1. 解决Type 'Any' cannot conform to 'Decodable'错误
Type 'Any' cannot conform to 'Decodable'
错误原因
responseDecodable(of:)方法要求传入的泛型类型必须遵循Decodable协议,但Any类型并未实现该协议,因此你传入的Dictionary<String, Dictionary<String, Any>>不符合方法要求。
解决方法
方案一:使用自定义Decodable模型(推荐)
根据接口返回的JSON结构,定义对应的Swift结构体/类并遵循Decodable协议。示例如下:
// 假设接口内层字典包含id和name字段 struct InnerItem: Decodable { let id: Int let name: String // 按需添加其他字段 } // 外层字典类型对应接口返回结构 typealias ResponseModel = [String: [String: InnerItem]]
之后调用responseDecodable时传入该模型类型:
AF.request(webservice, headers: headers) .authenticate(with: credential) .responseDecodable(of: ResponseModel.self) { response in switch response.result { case .success(let result): print(result) case .failure(let error): print(error) } }
方案二:直接处理原始数据
若暂时不需要自定义模型,可改用responseData获取原始Data,再通过JSONSerialization解析,和原URLSession逻辑一致:
AF.request(webservice, headers: headers) .authenticate(with: credential) .responseData { response in switch response.result { case .success(let data): do { if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: [String: Any]] { print(json) } } catch { print(error) } case .failure(let error): print(error) } }
2. 解决No exact matches in call to class method 'jsonObject'错误
No exact matches in call to class method 'jsonObject'
错误原因
response闭包的参数是AFDataResponse<Data?>类型,并非Data类型。你直接传入response!不符合JSONSerialization.jsonObject(with:)对参数类型的要求,该方法需要的是Data实例。
修正代码
从response中取出data属性,并先判断其不为nil:
AF.request(webservice, headers: headers) .authenticate(with: credential) .response { response in guard let data = response.data else { print("请求无返回数据") return } do { if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: [String: Any]] { print(json) } } catch let error as NSError { print(error) } }
内容的提问来源于stack exchange,提问作者user979331
相关产品推荐
相关产品推荐

