我正在尝试对问题类看起来像的问题数组列表进行编码:
import kotlinx.serialization.Serializable
@Serializable
data class Question(var id: Int?, var question: String, var
answers:ArrayList<Answer>)
Answer 类如下所示:
import kotlinx.serialization.Serializable
@Serializable
data class Answer(var id:Int?, var answer: String, var rightAnswer: Boolean)
这是我试图对数组列表进行编码的代码:
val questionsJSON = Json.encodeToString(quiz.questions)
此代码导致以下错误:
Caused by:
kotlinx.serialization.SerializationException: Serializer for class 'Question' is not found.
Mark the class as @Serializable or provide the serializer explicitly.
我应该提一下,我为获取 kotlinx-serialization 库所做的唯一一件事就是在 build.cradle 中添加依赖项,因为我不知道如何应用插件。
//Kotlin serialization
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.2")
更新:
我尝试将以下内容添加到我的 build.cradle 和 proguard-rules.pro 中,但我一直收到同样的错误。
build.cradle
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'org.jetbrains.kotlin.plugin.serialization' version '1.5.20'
}
proguard-rules.pro
-keepattributes *Annotation*, InnerClasses
-dontnote kotlinx.serialization.AnnotationsKt # core
serialization annotations
# kotlinx-serialization-json specific. Add this if you have
java.lang.NoClassDefFoundError
kotlinx.serialization.json.JsonObjectSerializer
-keepclassmembers class kotlinx.serialization.json.** {
*** Companion;
}
-keepclasseswithmembers class kotlinx.serialization.json.** {
kotlinx.serialization.KSerializer serializer(...);
}
# Change here com.yourcompany.yourpackage
-keep,includedescriptorclasses class
eu.lucasblommers.quizapp.**$$serializer { *; } # <-- change package name to your app's
-keepclassmembers class eu.lucasblommers.quizapp.** { # <-- change package name to your app's
*** Companion;
}
-keepclasseswithmembers class eu.lucasblommers.quizapp.** { # <-- change package name to your app's
kotlinx.serialization.KSerializer serializer(...);
}