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

Retrofit报错:无法为WeatherModel类创建调用适配器,如何解决?

问题解决:Retrofit调用适配器创建失败

问题原因

你的API接口方法既没有标记为suspend,也没有用Call/Response包裹返回类型,Retrofit无法找到对应的调用适配器来处理这种返回值,因此触发Unable to create call adapter错误。

解决方案

方案一:使用协程(推荐,适配你的仓库suspend方法)

修改API接口,给getForecast函数添加suspend关键字,返回类型保持WeatherModel即可:

interface WeatherAPI {
    @GET("forecast.json")
    suspend fun getForecast(
        @Query("key") key: String,
        @Query("q") coordinates: String,
        @Query("days") days: Int,
        @Query("aqi") aqi: String,
        @Query("alerts") alerts: String,
        @Query("lang") lang: String
    ): WeatherModel
}

Retrofit 2.6.0及以上版本自带协程支持,无需额外添加依赖,这样就能直接在suspend仓库方法中调用接口函数。

方案二:使用传统Call包裹返回类型

如果不想用协程,将接口返回类型改为Call<WeatherModel>:

interface WeatherAPI {
    @GET("forecast.json")
    fun getForecast(
        @Query("key") key: String,
        @Query("q") coordinates: String,
        @Query("days") days: Int,
        @Query("aqi") aqi: String,
        @Query("alerts") alerts: String,
        @Query("lang") lang: String
    ): Call<WeatherModel>
}

然后在仓库方法中调用execute()获取响应体:

override suspend fun getWeatherFromApi(coordinates: String): WeatherModel? {
    runCatching {
        weatherApiService.getForecast(
            key = "HERE_GOES_KEY",
            coordinates = coordinates,
            days = 3,
            aqi = "no",
            alerts = "no",
            lang = "es"
        ).execute().body()
    }.onSuccess {
        return it
    }.onFailure {
        Log.i("hello","${it.message}")
    }

    return null
}

额外注意事项

你的OkHttp日志拦截器版本5.0.0-alpha.2是测试版,和Retrofit 2.9.0依赖的OkHttp稳定版可能存在兼容性问题,建议替换为匹配的稳定版本:

implementation 'com.squareup.okhttp3:logging-interceptor:4.9.3'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 01:53:11