Kotlin Serialization and Json (Android)

October 11, 2019

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

@Serializable
class 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.nonstrict


val 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:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.