Kotlin Serialization and Json (Android)

Setup

Edit Project build.gradle.

buildscript {
    ...

    dependencies {
        ...
        classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
    }
}

Edit Module:app build.gradle

...

apply plugin: 'kotlin-android'

apply plugin: 'kotlinx-serialization'

...

dependencies {
    ...

    implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.13.0"

    ...
}

Apply the following to proguard-rules.pro.

-keepattributes *Annotation*, InnerClasses
-dontnote kotlinx.serialization.SerializationKt
-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(...);
}

Code

@Serializableclass Person(val name: String, @SerialName("nick_name") val nickName: String, val age: Int, val friends: List<String>)
// if json string has extra field which is not to be serialize into object, use non-strict mode// val json = Json(JsonConfiguration.Stable)val json = Json(JsonConfiguration.Stable.copy(strictMode = false))// val json = Json.nonstrictval jsonString = """{"name":"Desmond","nick_name":"King","age":40,"friends":["Jack","Mei Ru","Han"],"extra_field":"not used"}"""val person = json.parse(Person.serializer(), jsonString)val jsonData = json.stringify(Person.serializer(), person)

jsonData output

{"name":"Desmond","nick_name":"King","age":40,"friends":["Jack","Mei Ru","Han"]

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.