kotlin 错误:类未在其接口范围内注册多态序列化

mfuanj7w  于 2022-11-25  发布在  Kotlin
关注(0)|答案(1)|浏览(102)

我需要设置可序列化接口,以便在方法中使用任何数据类,例如数据:

@Serializable
interface Todo{}

@Serializable
data class userDataForRegistration(val name: String, val number: String, val password: String): Todo

@Serializable
data class userDataForLogin(val number: String, val password: String): Todo

@Serializable
data class contactForRemove(val id: String, val number: String): Todo

@Serializable
data class userData(val number: String)

@Serializable
data class message(val message: String)

示例方法,其中body -上述一些数据类:

class Connection {
   val client = OkHttpClient()
   // params: login, registration, contact
   fun sendData(url: String, param: String, body: Todo){
       var json = Json.encodeToString(body)
       var reqBody = RequestBody.create("application/json; charset=utf-8".toMediaTypeOrNull(), json)

       val request = Request.Builder()
           .url(url)
           .post(reqBody)
           .build()

       client.newCall(request).enqueue(object : Callback {
           override fun onFailure(call: Call, e: IOException) {
               println("error" + e)
           }
           override fun onResponse(call: Call, response: Response){
               var res = response.body?.string()
               when(param){
                   "login", "registration" -> {
                       try{
                           val objUser = Json.decodeFromString<User>(res.toString())
                           returnUser(objUser)
                    }
                       catch(e: Exception){
                           val mes = Json.decodeFromString<message>(res.toString())
                           returnMessage(mes)
                       }
                   }   
                   "contact" ->{
                       val mes = Json.decodeFromString<message>(res.toString())
                       returnMessage(mes)
                   }
               }
           }
       })
   }

但是如果我调用方法:

val userDataForLogin = userDataForLogin(etv_name.text.toString(), etv_pass.text.toString())
val response = connection.sendData("${ip_static.ip}/user/login", "login", userDataForLogin)

我得到错误:

@Serializable annotation is ignored because it is impossible to serialize automatically interfaces or enums. Provide serializer manually via e.g. companion object

我只需要使用TODO接口来使用方法中的任何数据类,对象和抽象类将不起作用,因为它使用数据类
我的插件也在build.gradle:

plugins {
id 'com.android.application' version '7.2.2' apply false
id 'com.android.library' version '7.2.2' apply false
id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
id 'org.jetbrains.kotlin.plugin.serialization' version '1.6.21'

}
我读到,Kotlin.plugin.serialization 1.6.2+正在使用序列化接口,但是idk我有什么问题...提前谢谢你!)

mnowg1ta

mnowg1ta1#

您不应该将@Serializable添加到接口中,请参阅有关多态序列化的文档。相反,您必须对实现进行注解,并可能注册相应的序列化程序。

相关问题