When you create a program, it’s natural to assume that the data will only be used by that program. However, there may come a time when you want to share your data with other programs or use data from another source. In these cases, you need to serialize your data so that it can be accessed in different formats and by different programs.
Additionally, programming often involves working with large amounts of data. You need to store the data somewhere to be able to access it quickly whenever necessary. Not every component or system will accept the data format you are currently using. Data sharing and exchange is critical in this age of APIs and complex frameworks.
Kotlin uses a process called data serialization to convert data into other compatible data formats. This process is important because it makes it possible for you to send a portable and compatible data format to another host or entity.
In this tutorial, we will learn about data serialization, and how to serialize data in Kotlin.
To jump ahead:
Developed by the team behind Android at Google, the Kotlin programming language has been specifically designed for Android development. It is a functional language that is easy to read and understand, and it offers many advantages for developing Android apps.
Code written in Kotlin is very readable, because it uses very few keywords compared to most other programming languages. This makes it easy to understand what the code is doing, which is important when working with large teams. This also means fewer bugs, because the code is more explicit.
As code is more readable and explicit, it’s also easier to refactor and change if necessary. Kotlin is also 100% interoperable with Java, which means that you can use it together with Java code in the same project. In other words, it’s very easy to prepare your existing projects for Kotlin by converting some of the code to Kotlin.
Data serialization is the process of converting data from one format to another. Kotlin’s kotlinx.serialization
library is widely used to serialize data. The first stable version of the kotlinx.serialization
library was released in October 2020, and it is regularly updated. The library has a Kotlin-based API that parses JSON into type-safe Kotlin objects.
The kotlinx.serialization
library is useful because it is Kotlin Multiplatform based. It is available in Kotlin/JS and Kotlin/Native. The library is good at serializing singletons, data classes, and generic lists. And, it approaches polymorphic serialization by using sealed hierarchies.
The kotlinx.serialization
library has a configuration DSL that allows you to configure the serialization input and output the way you want. You can ignore unknown keys and lenient parsing.
The library can be integrated with frameworks, such as Ktor to achieve content negotiations. Content negotiation occurs when your application requires a suitable resource presentation from the client. Spring MVC and Http4k also have support for the kotlinx.serialization
library. The library also supports the following formats:
However, the formats above may not be stable when compared to the JSON format when serializing data using the kotlinx.serialization library
.
A good thing about serialization is that it is not permanent. There is a way you can reverse data serialization using a process called data deserialization.
There are many reasons to use deserialization, one reason being to read data that was created during serialization. Another reason is if you want to create a copy of an object that was previously serialized. The advantage of deserialization is that you can read data from a string or file that was previously saved and then convert it back into a usable object.
Data deserialization also allows you to read data from other sources, such as files, network connections, databases, or the web. There are many advantages to using deserialization in programming. It can save time, reduce network traffic, and consume less space when storing data. The process of deserialization can also be used to convert data back into its original format. This process can be applied to any language that supports objects and classes.
In this section, we will learn how data serialization works in Kotlin by using functions from the kotlinx.serialization
library.
To start using kotlinx.serialization
in your project, simply add the compiler
plugin and runtime
library to your project. In your build.gradle
(app level), add the following entry to the plugin block:
apply plugin: 'kotlinx-serialization'
Now, add the following dependency in the build.gradle
(app level):
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.2"
Next, add the runtime library dependency to the dependencies block in your build.gradle
(project level) file:
classpath 'com.android.tools.build:gradle:7.0.2' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version" classpath "com.google.dagger:hilt-android-gradle-plugin:$dagger_version" classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
Create a Kotlin file called Car
and import the following classes from the kotlinx.serialization
library:
import kotlinx.serialization.Serializable import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json
In this tutorial, we will create a data class called Car
that takes in the names of cars and converts them to the JSON format, and then reconverts them to Kotlin objects. The data class will be annotated as @Serializable
to avoid runtime errors.
The @Serializable
annotation is used to indicate a class that serializes data. If you don’t add this annotation, you will experience a compile time error. To exclude the fields from the serialization process, use the @Trasient
annotation.
Now, create a data class called Car
, which will take in the following values listed in the Car
parenthesis:
@Serializable data class Car(val name: String, val model:String)
Next, serialize Kotlin objects to the JSON string by using the encodeToString
method that is used to convert Kotlin objects into JSON format:
fun main() { val garage = Car("Toyota", "Hilux") val string = Json.encodeToString(garage) println(string)
To deserialize the converted objects, use the decodeFromString<T>
method to convert the JSON format to a Kotlin object:
val obj = Json.decodeFromString<Car>(string) println(obj) }
If you run the above function in Android Studio, you will get the following output, which shows the converted Kotlin objects to JSON string and then reconverted back to Kotlin objects:
{"name":"Toyota","model":"Hilux"} Car(name=Toyota, model=Hilux) Process finished with exit code 0
There are many reasons you should serialize your data. First, it enables you to save your data in different formats. You’ll be able to access that data later, even after your program has been closed. Serialization also allows you to share your data with others, allowing you to access your data from anywhere.
Finally, serialization allows you to read and understand other formats. For example, let’s say you receive data from another company. If you use the right software, you’ll be able to easily read the data and use it for your own purposes.
Serialization also has its disadvantages. First and foremost, it takes time to perform serialization. Your computer will need to read your data and save it in a different format. If you are working with a large amount of data, this may take some time.
You also need to be careful when serializing sensitive data. This can include financial information or other data that you don’t want people to see. If you save this data in a file and share it with others, they will have access to it.
In this tutorial, you learned how to serialize and deserialize data in Kotlin using the kotlinx.serialization
library. We explored the many reasons why you should consider data serialization, as well as some of the disadvantages associated with serialization. In the end, it comes down to preference whether you choose to save your data in a format that humans can read or one that only computers can understand.
LogRocket is an Android monitoring solution that helps you reproduce issues instantly, prioritize bugs, and understand performance in your Android apps.
LogRocket also helps you increase conversion rates and product usage by showing you exactly how users are interacting with your app. LogRocket's product analytics features surface the reasons why users don't complete a particular flow or don't adopt a new feature.
Start proactively monitoring your Android apps — try LogRocket for free.
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowReact Native’s New Architecture offers significant performance advantages. In this article, you’ll explore synchronous and asynchronous rendering in React Native through practical use cases.
Build scalable admin dashboards with Filament and Laravel using Form Builder, Notifications, and Actions for clean, interactive panels.
Break down the parts of a URL and explore APIs for working with them in JavaScript, parsing them, building query strings, checking their validity, etc.
In this guide, explore lazy loading and error loading as two techniques for fetching data in React apps.