Kotlinx Serialization with Kotlin Native

In our earlier post, we have discussed kotlinx serialization vs Jackson. Lately, Kotlinx serialization released its stable first version 1.0. I thought now its time to explore how it behaves in the native counterpart of Kotlin. So here goes my experience on Kotlinx serialization with Kotlin native specifically on windows environment.

Setting up the project

I’m using IntelliJ Idea as my development environment. Currently, it’s the easy way of setting up Kotlin native project. You should have installed the Kotlin plugin to follow along. If you are not using IntelliJ Idea you could use Gradle straightly. But I guess it’s a rare case, who would use Kotlin without IntelliJ Idea, right?

Project wizard for Kotlin Native Application in IntelliJ Idea

Make sure to use Java 8 as the Gradle JVM. I faced problems when using Java 8+. After setting up your project name, it opens a basic native project. Since kotlin multiplatform is still in Alpha it could change over time. I realized that it was generating a different build Gradle file a few weeks earlier to the time of writing this. So I am going to tailor it to work on windows and hopefully it would remain for a longer period.

Kotlinx Serialization with Kotlin Native Gradle Build Script

plugins {
    id 'org.jetbrains.kotlin.multiplatform' version '1.4.20'
    id 'org.jetbrains.kotlin.plugin.serialization' version '1.4.10'
}
repositories {
    mavenCentral()
}
kotlin {
    // For ARM, should be changed to iosArm32 or iosArm64
    // For Linux, should be changed to e.g. linuxX64
    // For MacOS, should be changed to e.g. macosX64
    // For Windows, should be changed to e.g. mingwX64
    mingwX64("mingw") {
        binaries {
            executable {
                // Change to specify fully qualified name of your application's entry point:
               entryPoint = 'main'
                // Specify command-line arguments, if necessary:
                runTask?.args('')
            }
        }
    }
    sourceSets {
        // Note: To enable common source sets please comment out 'kotlin.import.noCommonSourceSets' property
        // in gradle.properties file and re-import your project in IDE.
        commonMain {
            dependencies {
                implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.0.1'
            }
        }
        commonTest {
        }
        mingwMain {
        }
        mingwTest {
        }
    }
}

// Use the following Gradle tasks to run your application:
// :runReleaseExecutableMingw - without debug symbols
// :runDebugExecutableMingw - with debug symbols

I ll explain top to bottom. Although I am not going to explain all configurations of Kotlin multiplatform Gradle plugin, you can read about it here. We need two plugins first one is a multiplatform plugin, make sure to use its latest. Then we need serialization plugin, use the latest version. Next, you need to have repositories section with maven central so we can grab dependencies from the maven central. The important section is the kotlin section. Since I am on windows, I should use mingwX64 target. You can read more about available targets here. Within the target, we can specify an entry point in the binaries executable section. Finally, the source sets. We can have different sources for different targets because of kotlinx serialization is supported by all platforms. I decided to put source code in the common source set. Based on your kotlin idea plugin version it would generate kotlin.import.noCommonSourceSets=true in gradle.properties file, remove it if you plan to use common source sets. Then IDE would import project with common source sets.

With this setup, you can build the application then it will produce binaries in build/bin/ inside particular target you working. You can run the executable after executing the Gradle build task. It would execute the entry point’s main method.

Kotlin native builds in bin directory

Add kotlinx serialization dependencies

If you had close look earlier to the build script. You may already found how to add dependencies to the common source set. I’ve added kotlinx serialization JSON dependency. Now we can write our first kotlinx serialization native program. This is a very small program, I just wanted to try kotlinx serialization on a native platform. You could read my previous article and write some decent serialization code if you want.

Serialize Kotlin Object

I am just serializing a Kotlin object to json string.

import kotlinx.serialization.Serializable

@Serializable
data class Person(var name: String)
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

fun main(){
    val jsonString = Json.encodeToString(Person("mark"))
    println(jsonString)
}

Here is how my classes are placed.

Kotlin classes location in common source set

Run gradle build and it would generate binaries in bin directory I mentioned earlier. Then run the application, it will generate following output.

kotlinx native serialization output

Deserialize Json String

import kotlinx.serialization.json.Json

fun main(args: Array<String>){
    val person = Json.decodeFromString(Person.serializer(), args[0])
    println(person.name)
}

Above program generates following output.

Kotlin native deserialization output

Final Words

Remember kotlin multiplatform projects are still in Alpha stage so at the time of reading above all may invalid. I’ll try to keep this post update as much as possible, so let me know if I forget. Thanks for reading and I invite you to try this out. Head over to my youtube channel to learn something new.

Leave a Comment

Your email address will not be published. Required fields are marked *