android - 无法创建转换器(Kotlin、Retrofit 和 Moshi)
问题描述
我在 Retrofit 中遇到了一个简单的 GET 请求问题。
我从返回许多我并不真正需要的对的 API 获取数据,因此我只关注在涉及此特定请求时需要解析的元素。
为了得到一个想法,这是响应的样子:
[
{
"buildingID": 0,
"buildingName": "string",
"description": "string",
"address": "string",
"type": 0,
"rooms": [
{
...
}
],
"reservations": [
{
...
}
]
...
}
我只想从中拉出几对,所以我创建了以下数据类:
@JsonClass(generateAdapter = true)
data class BuildingJson(@field:Json(name = "buildingID") val buildingID: Int,
@field:Json(name = "buildingName") val name: String,
@field:Json(name = "description") val description: String,
@field:Json(name = "address") val address: String,
@field:Json(name = "type") val type: Int)
这就是我的改造&moshi 实例的样子(Singleton.kt):
object Singleton {
val okhttp = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
})
.build()
val moshi = Moshi.Builder().build()
const val BASE_URL = "https://localhost:5001/api/"
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okhttp)
.addConverterFactory(MoshiConverterFactory.create())
.build()
val service = retrofit.create(BookitAPI::class.java)
}
这就是我的 Retrofit 调用接口的样子(包装在 BookitAPI.kt 中):
interface BookitAPI {
@GET("v1/BuildingApi")
fun getBuildings(): Call<List<BuildingJson>>
}
这一切都在存储库中使用以下代码调用:
val buildingResponse = service.getBuildings().enqueue(object : Callback<List<BuildingJson>> {
override fun onFailure(call: Call<List<BuildingJson>>, t: Throwable) {
TODO("Not yet implemented")
}
override fun onResponse(
call: Call<List<BuildingJson>>,
response: Response<List<BuildingJson>>
) {
TODO("Not yet implemented")
}
})
问题是,当我运行此代码时,出现以下错误:
java.lang.IllegalArgumentException: Unable to create converter for java.util.List<mylab.bookitphoneapp.models.BuildingJson>
for method BookitAPI.getBuildings
有谁知道我应该如何实现这个无法创建的转换器?我检查了很多资源,但仍然找不到与此类似的问题。
谢谢!