Retrofit挂起函数发起登录请求时出现JsonIOException错误排查
Retrofit登录请求报错:Interfaces can't be instantiated! (retrofit2.Call)
错误原因
你在Retrofit Service接口中使用了suspend挂起函数,但返回类型错误地用Call<LoginResponse>包裹。
Retrofit对suspend函数的设计逻辑是自动处理异步请求流程,直接返回响应对应的实体类,不需要用Call接口包裹。当Gson尝试解析响应体时,会把Call当成普通实体类去实例化,但Call是接口,无法被实例化,因此抛出该JsonIOException。
解决方法
修改Service接口的返回类型,移除Call包裹,直接返回实体类或Response包装类:
方案1:直接返回实体类(仅获取响应数据)
@FormUrlEncoded @POST("login") suspend fun authenticateUser(@Field("email") email: String, @Field("password") password: String): LoginResponse
方案2:返回Response包装类(获取完整响应信息)
如果需要访问响应码、响应头等完整请求信息,可使用Response<LoginResponse>作为返回类型:
@FormUrlEncoded @POST("login") suspend fun authenticateUser(@Field("email") email: String, @Field("password") password: String): Response<LoginResponse>
两种方案都能避免Gson尝试实例化Call接口的问题,同时符合Retrofit对suspend函数的使用规范。
内容的提问来源于stack exchange,提问作者onStackOverflowListener
相关产品推荐
相关产品推荐

