使用kotlin进行改造,无法创建@Body

jon*_*ney 2 android kotlin retrofit2

嗨,我得到以下错误:

 java.lang.IllegalArgumentException: Unable to create @Body converter for class com.jr.app.models.ExampleData (parameter #1)
Run Code Online (Sandbox Code Playgroud)

这是我的ExampleData.kt

data class ExampleData(val id: String,
                   val firstName: String,
                   val secondName: String,
                   val profilImages: String,
                   val info: String) {

}
Run Code Online (Sandbox Code Playgroud)

我的界面改造

interface UsersService {

@GET("/usersProfile")
fun getAllUsers(): Call<List<ExampleData>>

@POST("/usersProfile")
fun addUser(@Body exampleData: ExampleData): Call<ResponseBody>

}
Run Code Online (Sandbox Code Playgroud)

添加用户的功能

  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


}
Run Code Online (Sandbox Code Playgroud)

小智 5

将gradle依赖项添加到项目中:

compile 'com.squareup.retrofit2:converter-gson:VERSION_OF_RETROFIT'
Run Code Online (Sandbox Code Playgroud)

在构建改造实例时添加以下行:

.addConverterFactory(GsonConverterFactory.create())
Run Code Online (Sandbox Code Playgroud)

在您的项目构建中,改造对象将如下所示:

val retrofit = Retrofit.Builder()
    .baseUrl(baseUrl)
    .client(httpAuthClient)
    .addConverterFactory(GsonConverterFactory.create())
    .build()
Run Code Online (Sandbox Code Playgroud)