Kotlin Properties Serialization (encode data class to map)

Edit Project build.gradle

buildscript {
    ext {
        kotlin_version = '1.5.31'
    }

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

Edit Module build.gradle

plugins {
    id 'kotlinx-serialization'
}

dependencies {
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-properties:1.3.1"
}

Take note of Proguard Configuration for production release.

Sample Data class.

@Serializabledata class Card(    var id: String? = null,    @Serializable(TimestampSerializer::class)    var modified: Timestamp? = null,    var title: String? = null,)

NOTE: Timestamp

Sample Serializer

object TimestampSerializer : KSerializer<Timestamp> {    override val descriptor = PrimitiveSerialDescriptor("Timestamp", PrimitiveKind.LONG)    override fun deserialize(decoder: Decoder): Timestamp {        return Timestamp(Date(decoder.decodeLong()))    }    override fun serialize(encoder: Encoder, value: Timestamp) {        encoder.encodeLong(value.toDate().time)    }}

Usage

val card = Card(id = "test", modified = Timestamp.now(), title = "Hello World")var data = Properties.encodeToMap(Card.serializer(), this)

Note

  • Properties doesn't supported nested class, so the map generated is single level only
  • Properties which are class need to be converted to basic type via KSerializer implementation

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.