简体   繁体   English

用Kotlin进行改装,无法创建@Body

[英]Retrofit with kotlin, unable to create @Body

Hi i get the following error: 嗨,我收到以下错误:

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

Here is my ExampleData.kt 这是我的ExampleData.kt

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

}

My interface retrofit 我的界面改造

interface UsersService {

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

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

}

function that addsUser addUser的函数

  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


}

Add the gradle dependency to your project: 将gradle依赖项添加到您的项目中:

compile 'com.squareup.retrofit2:converter-gson:VERSION_OF_RETROFIT'

When you build an instance of retrofit add this line: 构建改造实例时,请添加以下行:

.addConverterFactory(GsonConverterFactory.create())

In your project building the retrofit object will look like: 在您的项目构建中,改造对象将如下所示:

val retrofit = Retrofit.Builder()
    .baseUrl(baseUrl)
    .client(httpAuthClient)
    .addConverterFactory(GsonConverterFactory.create())
    .build()

I believe this has nothing to do with Kotlin but your Retrofit configuration and your data class ExampleData. 我相信这与Kotlin无关,但与Retrofit配置和数据类ExampleData有关。

Retrofit has no idea how to serialize your instance of ExampleData to JSON. Retrofit不知道如何将您的ExampleData实例序列化为JSON。 You need to add a specific converter factory when creating instance of Retrofit client (see Builder#addConverterFactory method for details). 创建Retrofit客户端实例时,需要添加特定的转换器工厂(有关详细信息,请参见Builder#addConverterFactory方法)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM