简体   繁体   English

NoClassDefFoundError kotlinx 序列化

[英]NoClassDefFoundError kotlinx serialization

I have a kotlin multiplatform project and I need to serialize a class.我有一个 kotlin 多平台项目,我需要serialize一个 class。 I have included the following dependency in my commonMain and androidMain and iosMain respectively in my multiplatform gradle file :我在我的multiplatform gradle file中分别在我的commonMainandroidMainiosMain中包含以下依赖项:

 //commonMain
 implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:0.20.0"

 //androidMain
 implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.20.0"

 //iosMain
 implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime-native:0.20.0"

This is the class I want to serialize :这是我要serialize的 class :

@Serializable
class Test {

    fun toJsonTestClass() = Json.stringify(Test.serializer(), this)
    var value1:Double = 0.toDouble()
       
    companion object {

        fun buildClass(value1 : Double):Test {

            val test = Test()
            test.value1 = value1
   
            return test
        }

         fun fromJsonTestClass(json:String) = Json.parse(Test.serializer(), json)
    }
}

And in another class ( TrialClass ), this is how I am testing it:在另一个 class ( TrialClass )中,这就是我测试它的方式:

val test = Test()
val testToJson = test.toJsonTestClass() //<- This is where the error is pointing to.

println(testToJson)

But when I run it, I get the following error:但是当我运行它时,我收到以下错误:

 Exception in thread "main" java.lang.NoClassDefFoundError: kotlinx/serialization/json/Json at Test.toJsonTestClass(Test.kt:28) at TrialClass.main(TrialClass.kt:4) Caused by: java.lang.ClassNotFoundException: kotlinx.serialization.json.Json

I get no issues when having the imports in my class, but when running I get the above mentioned error.在我的 class 中导入时我没有遇到任何问题,但是在运行时我得到了上述错误。

Any help or advice will be highly appreciated.任何帮助或建议将不胜感激。

For my case, I did everything right - code & configuration.就我而言,我做的一切都是正确的——代码和配置。 And gradle clean didn't help, I ended up with the magic Invalidate Caches / Restart from IntelliJ IDEA. gradle clean并没有帮助,我最终从 IntelliJ IDEA 获得了神奇的Invalidate Caches / Restart

Your class is probably being obfuscated.您的 class 可能被混淆了。 You have two options:你有两个选择:

Add the @Keep annotation above the class:在 class 上方添加@Keep注释:

@Serializable
@Keep
class Teste {
// ...
}...

or add it to your module's proguard:或将其添加到模块的 proguard 中:

-keep (path_to_the_class).test.** { *; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM