首页 > 解决方案 > java.lang.IllegalArgumentException:无法为类创建@Body 转换器

问题描述

最近我从 GSONConverterFactory 切换到 MoshiConverterFactory。除了一个电话,一切都很好。像这里的其他 API 调用一样,我也在使用 @Body 注释,但我收到此错误 java.lang.IllegalArgumentException: Unable to create @Body converter for class

我的请求类:

data class DemoRequest(
val emailId: String? = null,
val demoData: List<DemoDomain?>? = null,
val userName: String? = null

)

这里还有一件事要提到的是,使用 GSONConverterFactory 它工作正常,但是当我切换到 MoshiConverterFactory 时,它会抛出错误。

改造版本 = '2.3.0'

服务接口:

@POST("call/api")
fun sendToServer(@Body request: DemoRequest):retrofit2.Call<RemoteResponse>

val retrofit = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(okHttpClient)
            .addConverterFactory(MoshiConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()

更新------------- 我在请求中发送 Date 对象,所以我需要使用自定义适配器,它现在工作正常

标签: androidretrofit2moshi

解决方案


您是否记得在构建 Retrofit 时更改为MoshiConverterFactory

Retrofit.Builder().baseUrl(...).addConverterFactory(MoshiConverterFactory.create()).build()

此外,Retrofit 的最新版本是 2.5.0,因此您可以尝试升级并确保您的转换器也是相同的版本。


推荐阅读