您好我收到以下错误:
java.lang.IllegalArgumentException: Unable to create @Body converter for class com.jr.app.models.ExampleData (parameter #1)
这是我的ExampleData.kt
data class ExampleData(val id: String,
val firstName: String,
val secondName: String,
val profilImages: String,
val info: String) {
}
我的界面改造
interface UsersService {
@GET("/usersProfile")
fun getAllUsers(): Call<List<ExampleData>>
@POST("/usersProfile")
fun addUser(@Body exampleData: ExampleData): Call<ResponseBody>
}
添加用户的功能
override fun addUser(user: ExampleData) {
val retrofit = Retrofit.Builder().baseUrl(baseUrl).client(httpAuthClient).build();
val userService = retrofit.create(UsersService::class.java);
userService.addUser(user).enqueue(callbackResponse);
}
private val httpAuthClient: OkHttpClient
get() {
val okHttpClient = OkHttpClient().newBuilder().addInterceptor { chain ->
val originalRequest = chain.request()
val builder = originalRequest.newBuilder().header(authorizeHeader,
Credentials.basic(userName, password))
val newRequest = builder.build()
chain.proceed(newRequest)
}.build()
return okHttpClient
}
答案 0 :(得分:5)
将gradle依赖项添加到项目中:
compile 'com.squareup.retrofit2:converter-gson:VERSION_OF_RETROFIT'
当您构建改造实例时,请添加以下行:
.addConverterFactory(GsonConverterFactory.create())
在您的项目构建中,改造对象将如下所示:
val retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.client(httpAuthClient)
.addConverterFactory(GsonConverterFactory.create())
.build()
答案 1 :(得分:1)
我认为这与Kotlin无关,而是与您的Retrofit配置和数据类ExampleData无关。
Retrofit不知道如何将ExampleData实例序列化为JSON。您需要在创建Retrofit客户端实例时添加特定的转换器工厂(有关详细信息,请参阅Builder#addConverterFactory
方法)。