IDEA如何使用kotlinx.serialization?


#1

IDEA中使用kotlinx.serialization,通常是在gradle中加入相关配置可正常使用,如:
plugins {
kotlin(“jvm”) version “1.4.0”
application
id(“org.jetbrains.kotlin.plugin.serialization”) version “1.4.10”
}
如不用Gradle,仅仅使用IDEA自带的Kotlin编译器(由相应插件提供),已下载org.jetbrains.kotlinx:kotlinx-serialization-core:1.0.0-RC和org.jetbrains.kotlin:kotlin-serialization:1.4.10两个库,下列代码编译时可正常通过,但无法正常执行。
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
@Serializable
data class ProjectX(val name: String, val language: String)

fun main(){
val data1 = ProjectX(“kotlinx.serialization”, “Kotlin”)
println(Json.encodeToString(data1))

val data2 = Json.decodeFromString<ProjectX>("""
    {"name":"kotlinx.serialization","language":"Kotlin"}
""")
println(data2)

}
报错:Exception in thread “main” kotlinx.serialization.SerializationException: Serializer for class ‘ProjectX’ is not found.
Mark the class as @Serializable or provide the serializer explicitly.
at kotlinx.serialization.internal.Platform_commonKt.serializerNotRegistered(Platform.common.kt:127)
at kotlinx.serialization.SerializersKt__SerializersKt.serializer(Serializers.kt:56)
at kotlinx.serialization.SerializersKt.serializer(Unknown Source)
at SerilizationKt.main(serilization.kt:31)
at SerilizationKt.main(serilization.kt)
主要原因是编译器不认@Serializable注解,有解决办法吗?


京ICP备16022265号-2 Kotlin China 2017 - 2018