Skip to content
DeveloperMemos

Using Kotlin Serialization in an Android Project

Android, Serialization, Kotlin1 min read

Today I thought I'd write a quick post about using Kotlin Serialization in an Android project. I'm going to specifically write about JSON serialization.

Why use Serialization?

There are a few reasons why you might want to use Serialization. In my specific case I had a data class that I wanted to save to SharedPreferences. This isn't the best practice. If you have a complicated, large set of data you really should be using Room or Realm - or something else along those lines. In my case the data is really simple and it's a small set. I actually used Realm in the past for this specific project and I ended up overengineering and migrating back to SharedPreferences eventually anyway.

There are definitely other reasons that you might want to use serialization, like for decoding JSON responses from an API.

Setup

So to use Kotlin Serialization in your project you'll need to add some dependencies. First of all, in your project-level build.gradle file you need to add this to your plugins:

1plugins {
2 ...
3 // Add this
4 id 'org.jetbrains.kotlin.plugin.serialization' version '1.7.20'
5}

Make sure that the version you are using is the same as the Kotlin version for your project. For this project I'm using Kotlin 1.7.20.

Next you need to apply the plugin in your app-level build.gradle. For most people this should be right at the top:

1plugins {
2 id 'com.android.application'
3 ...
4 // Add this
5 id 'kotlinx-serialization'
6}

And while you're there, for JSON serialization you need to add this to your dependencies block:

1implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.4.1"

Also make sure that you check what the latest version is, this article is current as of November 2022.

The data class

So say that you have an example data class in place already, 'FooData':

1data class FooData(
2 val name: String = "Foo",
3 val number: Int = 1
4)

All you need to do to this class is add the @Serializable annotation:

1@Serializable
2data class FooData(
3 val name: String = "Foo",
4 val number: Int = 1
5)

And you're ready to go! So let's encode and decode some JSON.

Encoding and decoding

It's all pretty straight-forward. If you have an object, you just need to use Json.encodeToString to encode it:

1val foo = FooData(
2 name = "test",
3 number = 20
4)
5val jsonString = Json.encodeToString(foo)

And here's what jsonString looks like if you log it:

1{"name":"test","number":20}

You can then use Json.decodeFromString to decode JSON from a string:

1// {"name":"test","number":20}
2val jsonString = Json.encodeToString(foo)
3val decodedFoo = Json.decodeFromString<FooData>(jsonString)

This all works for Lists of the @Serializable class too! Keep in mind though if you are using a custom class for any of the values you will need to create a custom serializable for things to work - but that's a topic for another post.