androidkotlinserializablekotlinx.serialization

Serializer for data class Kotlin not found at build release


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

Solution

  • 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!!