序列化

    Some data serialization formats, such as and protocol buffers are particularly common. Being language-neutral and platform-neutral, they enable data exchange between systems written in any modern language.

    In Kotlin, data serialization tools are available in a separate component, . It consists of two main parts: the Gradle plugin – and the runtime libraries.

    kotlinx.serialization provides sets of libraries for all supported platforms – JVM, JavaScript, Native – and for various serialization formats – JSON, CBOR, protocol buffers, and others. You can find the complete list of supported serialization formats below.

    All Kotlin serialization libraries belong to the org.jetbrains.kotlinx: group. Their names start with kotlinx-serialization- and have suffixes that reflect the serialization format and the target platform, such as -js or -native. Libraries for the JVM and for the common code of multiplatform projects contain no suffix. Examples:

    • org.jetbrains.kotlinx:kotlinx-serialization-core provides JSON serialization on the JVM.
    • org.jetbrains.kotlinx:kotlinx-cbor-js provides CBOR serialization on the JavaScript platform.

    Note that kotlinx.serialization libraries use their own versioning structure, which doesn’t match the Kotlin’s. Check out the releases on to find the latest versions.

    • JSON: kotlinx-serialization-core
    • : kotlinx-serialization-cbor
    • Properties: kotlinx-serialization-properties
    • : kotlinx-serialization-hocon (only on JVM)

    Note that all libraries except JSON serialization (kotlinx-serialization-core) are in the experimental state, which means their API can be changed without notice.

    There are also community-maintained libraries that support more serialization formats, such as YAML or . For detailed information about available serialization formats, see the kotlinx.serialization documentation.

    Let’s take a look at how to serialize Kotlin objects into JSON.

    Before starting, you’ll need to configure your build script so that you can use Kotlin serialization tools in your project:

    1. Apply the Kotlin serialization Gradle plugin org.jetbrains.kotlin.plugin.serialization (or kotlin(“plugin.serialization”) in the Kotlin Gradle DSL).

      1. plugins {
      2. kotlin("jvm") version "1.4.20"
      1. dependencies {
      2. implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.0.1")
      3. }

    Now you’re ready to use the serialization API in your code.

    First, make a class serializable by annotating it with @Serializable.

    You can now serialize an instance of this class by calling Json.encodeToString().

    1. Json.encodeToString(Data(42))

    As a result, you get a string containing the state of this object in the JSON format: {"a": 42, "b": "str"}

    You can also serialize object collections, such as lists, in a single call.

      For more information about serialization in Kotlin, see the .