【问题标题】:Codables error with Alamofire "Cannot convert value of type '[String : Any]' to expected argument type 'Data'"Alamofire 的 Codables 错误“无法将 '[String : Any]' 类型的值转换为预期的参数类型 'Data'”
【发布时间】:2020-02-27 11:26:42
【问题描述】:

我通过使用 Alamofire 从 API 获得响应,该响应采用 [String:Any] 的形式,我正在尝试将该响应转换为可编码格式,它显示错误“无法转换类型的值 '[String:Any] ]' 到预期的参数类型“数据”。

请找到我的以下代码并帮助我。

func apiHandling(){
        Alamofire.request(catrgeryurl, method: .get, parameters: nil, headers: nil).responseJSON { (response) in
            if response.result.value != nil{
                if let data = response.result.value as? [String:Any]{
                    if let myStruct = try? JSONDecoder().decode(Mainsite.self, from: data) {
                        //do something with myStruct
                        print(myStruct)
                    } else {
                        //handle myStruct being nil
                    }
                }
            }
        }
    }

【问题讨论】:

    标签: ios json swift alamofire codable


    【解决方案1】:

    JSONDecoder 需要 Data 而不是字典。这就是错误告诉你的内容。

    responseJSON 替换为responseData,这是处理响应的推荐语法。

    func apiHandling(){
        Alamofire.request(catrgeryurl).responseData { response in
            switch response.result {
            case .success(let data):
                do {
                    let myStruct = try JSONDecoder().decode(Mainsite.self, from: data)
                } catch { print(error) }
            case .failure(let error): print(error)
            }
        }
    }
    

    【讨论】:

    • 这里 myStruct 给出了 nil 值。
    • 这是另一个问题,如果不了解 JSON 和结构,就无法回答。实际上你应该得到一个错误,而不是nil
    猜你喜欢
    • 2020-02-04
    • 2021-06-18
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多