用kotlin改造,无法创建@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 }
将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()
我相信这与Kotlin无关,但是您的Retrofit配置和您的数据类ExampleData无关。
改造不知道如何序列化你的ExampleData实例到JSON。 在创建Retrofit客户端的实例时,您需要添加特定的转换器工厂(有关详细信息,请参阅Builder#addConverterFactory
方法)。