接收 com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: 加载字节数据作为 Retrofit 的响应时出错

问题描述

我正在从对服务器的 API 调用中以 Byte data 的形式接收图像。但是当我收到 Retrofit2 Response 时,它​​会导致上述错误。顺便说一句,这是我的应用程序改造对象:

object RetrofitInstance {
        private val client = OkHttpClient.Builder().apply {
        addInterceptor(MyInterceptor())
        addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
    }.build()
private val retrofit by lazy {
    val gson = GsonBuilder().setLenient().create()
    Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(client)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build()
    }
val api : ApplicationAPI by lazy {
        retrofit.create(ApplicationAPI::class.java)
    }

我不知道为什么会出现 Json 语法异常。我相信这可能是因为我创建的 gson 客户端?有人可以帮我解决这个问题。在此先感谢您。

解决方法

尝试给予

addConverterFactory(MoshiConverterFactory.create())

并在 build.gradle 中添加以下行

implementation "com.squareup.retrofit2:converter-moshi:2.9.0"

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...