Kotlinx.serialization

kotlin
#1

Kotlinx.serialization is a handy tool which will often have his place in our developments.

It is a multiplatform serialization tool that works in Kotlin/JVM, Kotlin/JS and Kotlin/Native. It supports out of the box: JSON, Protobuf, CBOR.

Using it is very simple:

import kotlinx.serialization.*
import kotlinx.serialization.json.Json

@Serializable
data class Data(val a: Int, val b: String = "42")

fun main(args: Array<String>) {
    // serializing objects
    val jsonData = Json.stringify(Data.serializer(), Data(42))
    // serializing lists
    val jsonList = Json.stringify(Data.serializer().list, listOf(Data(42)))
    println(jsonData) // {"a": 42, "b": "42"}
    println(jsonList) // [{"a": 42, "b": "42"}]

    // parsing data back
    val obj = Json.parse(Data.serializer(), """{"a":42}""") // b is optional since it has default value
    println(obj) // Data(a=42, b="42")
}

Use cases

Compact file storage

During the process of collecting and transforming data, it is very useful to be able to store raw data into files. It is the best guaranty to keep all the collected data for example before any treatment. In that case, Kotlinx.serialization with Protobuf protocol is very fast and compact. With a few lines of code, the data classes are stored and retrieved on the file system.

Client-server communication

Kotlinx.serialization can also be used in the context of Client-server communication. We must do some tests. In the context of a Kotlin/JS client, inside a browser, the JSON.parse() method of the browser may be more performant than using a more compact protocol.