Kotlin Properties Serialization (encode data class to map)

December 16, 2021

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.

@Serializable
data 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:

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