2017-08-14 64 views
0

嗨,我得到以下錯誤:改造與科特林,無法創建@Body

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 


} 

回答

2

添加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

我相信這與Kotlin無關,但您的Retrofit配置和您的數據類ExampleData無關。

Retrofit不知道如何將ExampleData的實例序列化爲JSON。創建Retrofit客戶端實例時,需要添加特定的轉換器工廠(有關詳細信息,請參閱Builder#addConverterFactory方法)。