3
votes

I want convert my json string response from API to object:

val obj = Json.decodeFromString<MyModel>(jsonResponseString)

My data class:

@Serializable
data class MyModel(
    @SerializedName("field") val field: String
)

It look like very simple and it works on debug mode!

But when a compiled the AppBundle, builded in release mode and download app from Play Store internal testing, I got the following error :

Serializer for class '...' is not found. Mark the class as @serializable or provide the 
serializer explicitly.
kotlinx.serialization.internal.Platform_commonKt.serializerNotRegistered
2

2 Answers

3
votes

You should add this to your proguard.pro if you're using minifyEnabled true

-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 com.yourcompany.yourpackage.**$$serializer { *; } # <-- change package name to your app's
-keepclassmembers class com.yourcompany.yourpackage.** { # <-- change package name to your app's
    *** Companion;
}
-keepclasseswithmembers class com.yourcompany.yourpackage.** { # <-- change package name to your app's
    kotlinx.serialization.KSerializer serializer(...);
}

Make sure you replace the placeholder package name with your app package name

Source

2
votes

I found the next solution:

First step, I added @Keep anotation. Keep anotation denotes that the annotated element should not be removed when the code is minified at build time:

@Keep
@Serializable
data class MyModel(
    @SerializedName("field") val field: String
)

Second step, I converted my json to object making a static reference to the serializer:

val objError = Json {ignoreUnknownKeys = true}.decodeFromString(MyModel.serializer(), jsonResponseString)

Dont forget import and implement last version of:

'org.jetbrains.kotlin.plugin.serialization'

And it worked and it save my day!!