Introduction to Kotlin Serialization

1. Overview

In this article, we will see the Kotlin serialization.

Serialization is converting an object used by your application to a format that can be transferred over a network or stored in a database or a file, whereas deserialization allows us to reverse the process by reading the data from an external source and converting it back into an actual object.

Serialization format JSON is common and applies equally to all languages and platforms. It enables data exchange between systems written in any modern language.

We will discuss the JSON serialization in the following sections.

2. Kotlin serialization library

In Kotlin, data serialization tools are available in a separate component kotlinx.serialization. It comprises two key parts:

  • the Gradle plugin org.jetbrains.kotlin.plugin.serialization 
  • the library dependencies

2.1. Configure your project

Kotlin Serialization requires the Kotlin compiler 1.4.0 or higher.

1.Apply the serialization gradle plugin org.jetbrains.kotlin.plugin.serialization.

plugins {
    kotlin("jvm") version "1.5.30" 
    kotlin("plugin.serialization") version "1.5.30"
}
(OR)
buildscript {
    repositories { mavenCentral() }
    dependencies {
        val kotlinVersion = "1.5.30"
        classpath(kotlin("gradle-plugin", version = kotlinVersion))
        classpath(kotlin("serialization", version = kotlinVersion))
    }
}
apply plugin: 'kotlin' 
apply plugin: 'kotlinx-serialization'
plugins {
    id 'org.jetbrains.kotlin.multiplatform' version '1.5.30'
    id 'org.jetbrains.kotlin.plugin.serialization' version '1.5.30'
}
(OR)
buildscript {
    ext.kotlin_version = '1.5.30'
    repositories { mavenCentral() }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
    }
}
apply(plugin = "kotlinx-serialization")
apply(plugin = "kotlin")

2. Add the JSON serialization library dependency: org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0-RC

dependencies {
    implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0-RC'
}
dependencies {
    implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0-RC'
}

You can import the necessary APIs from kotlinx.serialization package for serialization.

3. Kotlin Json serialization

Consider you want to send your data as a JSON string to another system or store it in a database. It involves two steps.

  • Serialization
  • Encoding

The former Serialization converts the object into a serial sequence of its making up primitive values. This process is common for all data formats and its result depends on the object being serialized. A serializer controls this process.

The latter encoding converts the corresponding sequence of primitives into the output format representation. An encoder controls this process. 

The reverse process starts with parsing of the input format and decoding of primitive values, followed by deserialization of the resulting stream into objects.

3.1. JSON serialization implementation

Let’s make a class serializable by using the @Serializable annotation. This annotation is the primary entry point to the serialization process and instructs the serialization plugin to auto-generate the implementation of the serializer for the annotated class. Serializer helps to serialize the class.

We have the following two functions to convert the Object to String and vice versa

  • encodeToString - serializes the object that is passed as its parameter under the hood and encodes it to a JSON string.
  • decodeFromString - decodes the JSON string to primitive values and then deserializes it to object

The above functions and JSON specific sub-packages are available in the package kotlinx.serialization.json and you had to import this package for the JSON serialization.

3.2. Kotlin json serialization examples

Let’s see few examples for JSON serialization.

3.2.1 Kotlin data class serializable

You can specify your data class with @Serializable annotation and it serializes all the variables in the data class. When you call the encodeToString function passing the data class instance, it then converts the object to a JSON string.

3.2.1.1. Kotlin data class serialization example

Suppose you want to send the student information from your application to another application through the network as JSON. Let’s think that both the applications are in Kotlin.

In your application, annotate the data class StudentModel with @Serializable. If you pass an instance of the StudentModel as a parameter to the Json.encodeToString, it will convert the instance object to JSON string. You can send this JSON string to the destination application through the network.

@Serializable
data class StudentModel(val name: String, val department: String, val studentId: Long) {
    private var supervisor : String? = null
    constructor(name: String, department: String, studentId: Long, supervisor: String): this(name, department, studentId) {
        this.supervisor = supervisor
    }
    override fun toString(): String {
        return "StudentModel(name='$name', department='$department', studentId=$studentId, supervisor=$supervisor)"
    }
}
fun main() {
   val value = Json.encodeToString(StudentModel("Praj", "CS", 213, "Sakthi"))
   println(value) 
}

At the receiving end, the other application can perform deserialization using the decodeFromString method.

 import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json val obj = Json.decodeFromString<StudentModel>(""" {"name":"Praj","department":"CS","studentId":213,"supervisor":"Sakthi"} """) println(obj) 

3.2.2 Kotlin list serializable

You can also serialize object collections. For example, let’s create a list of student objects studentList and serialize them as a JSON string.

Using the encodeToString function, you can convert it into a JSON string. The JSON string contains an array of JSON objects. Each JSON object corresponds to the student object.

        val studentList = listOf(StudentModel("Praj", "CS", 213, "Sakthi"),
            StudentModel("Siv", "CS", 214))
        val jsonList = Json.encodeToString(studentList)
        println(jsonList) 

You can use the decodeToString function to convert the JSON string to an object.

import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
        val list = Json.decodeFromString("""[{"name":"Praj","department":"CS","studentId":213,"supervisor":"Sakthi"},{"name":"Siv","department":"CS","studentId":214}]
""")
        println(list)

4. Conclusion

In this article, we learned the Kotlin serialization.

Leave a Comment