首页 > 解决方案 > 无法使用 Moshi AND R8 序列化 Kotlin 类型

问题描述

我有这个奇怪的问题。当使用 R8 的 minify/obfuscation 时出现以下错误

java.lang.IllegalArgumentException: Cannot serialize Kotlin type <omitted>auth.model.ErrorResponse. Reflective serialization of Kotlin classes without using kotlin-reflect has undefined and unexpected behavior. Please use KotlinJsonAdapter from the moshi-kotlin artifact or use code gen from the moshi-kotlin-codegen artifact.

没有缩小/混淆一切都可以。我在用着

     val moshi = Moshi.Builder()
                .add(BigDecimalAdapter)
                .add(KotlinJsonAdapterFactory())
                .build()

正如moshi的自述文件所述。我也在使用 gradle

 implementation("com.squareup.moshi:moshi-kotlin:1.9.3")

并添加了规则

-keep class com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
-keep class <omitted>auth.model.ErrorResponse

但仍然有同样的例外。我错过了什么?

谢谢

更新

这是我的 BigDecimalAdapter

object BigDecimalAdapter {
    @FromJson
    fun fromJson(string: String) = BigDecimal(string)

    @ToJson
    fun toJson(value: BigDecimal) = value.toString()
}

标签: android

解决方案


尝试添加到您的 proguard:

-keepclassmembers class * {
    @com.squareup.moshi.FromJson <methods>;
    @com.squareup.moshi.ToJson <methods>;
}

推荐阅读