gitmyhub

kotlinx.serialization

Kotlin ★ 5.9k updated 3d ago

Kotlin multiplatform / multi-format serialization

Kotlin/kotlinx.serialization is a library from JetBrains that handles converting Kotlin data objects into text formats and back again. When you have a piece of data in your app, like a user profile or a product record, this library can turn it into JSON text for sending to a server, and then convert incoming JSON text back into a usable object. It supports multiple formats beyond JSON, including Protobuf, CBOR, HOCON, and Properties files.

The library works across different platforms: Android, desktop JVM apps, JavaScript runtimes, and native applications all use the same code and annotations. This is part of Kotlin's multiplatform approach, where a single codebase can target many environments without rewriting the serialization logic for each one.

Setting it up involves two steps. First, you add a compiler plugin to your build configuration (Gradle or Maven), which reads your data classes at compile time and generates the code needed to serialize them. Second, you add the runtime library as a dependency. Then you mark any data class with @Serializable and call functions like Json.encodeToString() to produce JSON text, or Json.decodeFromString() to convert JSON back into your object. The README includes a short, working example showing both directions.

For Android developers, the library includes ProGuard rules that keep serialization working after your app is minified for release. There is one caveat: if your data classes use named companion objects, a Kotlin language feature, you need to add a small set of extra ProGuard rules by hand. The README provides example rules for both standard ProGuard and R8, the newer code shrinker used in modern Android builds.

The project is an official JetBrains library released under the Apache 2.0 license. New versions are published in tandem with each Kotlin compiler release, so it stays current with the language. Full documentation, a detailed serialization guide, and an API reference are available on the official Kotlin documentation site.