在调用onResponse()/onFailure()之前,通过使用Kotlin和Retrofit,在响应http post时引发以下异常:
对于缺少类鉴别器('null') JSON输入:{"CustID":101,"DeviceID":81},未找到JSON多态序列化器。
不过,我只是使用一个简单的数据类,没有多态性。我在这里错过了什么?
我的数据对象(我添加了很多装饰来调试它):
@SerialName("NewCustVals")
@Serializable
data class NewCustVals (
@SerialName("CustID")
var CustID: Int? = 0,
@SerialName("DeviceID")
var DeviceID: Int? = 0
)
我的服务:
interface LTECustomerInterface {
companion object {
private var TAG :String = "LTECustomerInterface"
var BASE_URL = "http://XXXXXXXXXXX:XXXX/" //test server
lateinit var callbackApi :ApiCallback
@OptIn(ExperimentalSerializationApi::class)
fun create(cb:ApiCallback): LTECustomerInterface {
callbackApi = cb
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(Json{ignoreUnknownKeys = true; isLenient = true}.asConverterFactory( "application/json".toMediaType()))
// .client(client)
.build()
return retrofit.create(LTECustomerInterface::class.java)
}
}
@POST("/newCustomer")
suspend fun newCustomer(@Body data : Customer ) :Call<NewCustVals>
}
呼吁:
fun sendCustomer() {
viewModelScope.launch(Dispatchers.IO) {
val call = serverCustomerHttpInterface.newCustomer(_currentCust.value)
call.enqueue(object : retrofit2.Callback<NewCustVals>{
override fun onResponse(call: Call<NewCustVals>, response: Response<NewCustVals>) {
Log.i(TAG,"NewCustomer onResponse called")
}
override fun onFailure(call: Call<NewCustVals>, t: Throwable) {
Log.i("sendCustomer()","NewCustomer onFailure")
}
})
}
}
对于Retrofit/Kotlin来说,这是相当新鲜的,我猜我错过了一些很明显的东西。任何想法都将不胜感激。
谢谢
发布于 2022-07-25 05:50:52
您是否可以将返回类型从call更改为响应,并进行必要的更改和检查。
当我们愿意使用它的队列回调函数时,"Call“很有用。
当我们在项目中使用Coroutines或RxJava (这是最好的专业实践)来提供异步执行时,我们不需要队列回调。我们只需要回应。
由于我们没有使用回调,所以不会触发多态。
发布于 2022-09-27 05:52:02
尝试将调用接口更改为更新接口中的响应。
@POST("/newCustomer")
suspend fun newCustomer(@Body data : Customer ) :Call<NewCustVals>
至
@POST("/newCustomer")
suspend fun newCustomer(@Body data : Customer ) :Response<NewCustVals>
https://stackoverflow.com/questions/73101609
复制相似问题