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

使用Retrofit2发起HTTP请求时如何解决JsonIOException问题

Retrofit + GsonConverter 实例化接口错误排查

问题描述

项目此前运行正常,使用Retrofit搭配GsonConverter请求服务器列表时突然抛出以下错误:

FATAL EXCEPTION: main
com.google.gson.JsonIOException: Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter for this type. Interface name: retrofit2.Call
at com.google.gson.internal.ConstructorConstructor$3.construct(ConstructorConstructor.java:136)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$FieldReflectionAdapter.createAccumulator(ReflectiveTypeAdapterFactory.java:427)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:383)
at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:40)
at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:27)
at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:243)
at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:153)
at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:519)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
Suppressed: kotlinx.coroutines.DiagnosticCoroutineContextException: [StandaloneCoroutine{Cancelling}@b5910a6, Dispatchers.Main.immediate]

已尝试清理项目、重建、失效缓存,问题仍存在。

解决方案

  • 检查数据实体类:确认实体类中没有将retrofit2.Call作为字段类型。Gson尝试实例化该接口,说明实体类错误地把Call定义为了返回数据的字段——Call是Retrofit封装请求的类型,不能作为接口返回数据的字段。
  • 核对Retrofit接口方法:确保接口方法返回值类型正确。如果用协程挂起函数,应直接返回实体类/列表,而非Call<实体类>;如果用传统回调,返回Call<实体类>是合法的,但要避免Gson错误解析该类型。
  • 排查Gson配置:若自定义了Gson实例,确认没有错误地将Call类型纳入解析范围,或给Call注册了错误的TypeAdapter。
  • 检查依赖兼容性:通过./gradlew dependencies查看依赖树,确认Retrofit与Gson版本兼容,排除重复或冲突的依赖包。
  • 验证服务器返回结构:确认服务器返回的JSON结构与实体类完全匹配,排查是否新增未知字段、字段类型不匹配导致Gson解析异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 14:12:44