Docs: Kotlin Serialization Guide (#933)


Documentation from the docs folder is incorporated into a common story that spans six chapters and proceeds from the basic serialization to the experimental alternative and custom formats. The example files are automatically generated from the text with the Knit tool (guide/example folder) and are verified with the automatically generated tests (guide/test folder).

The entry point to the new is docs/serialization-guide.md that contains the overall table of contents and links to the specific chapters.

The old docs that are being incorporated:
* cbor_byte_string.md -> formats.md
* custom_serializers.md -> serializers.md
* examples.md -> basic-serialization.md
* json_transformations.md -> json.md
* old12.md (removed completely as obsolete)
* runtime_usage.md -> various chapters

Additional changes include:
* Top-level README.md file is cleaned up from legacy information and also contains a modern knitted example.
* More consistent error messages in various exceptions.
* Minor corrections to KDocs and APIs.
* Better style.css for the documentation that is generated by Dokka.
* Improved update_docs.sh to put temporary files inside the build folder.

Co-authored-by: Vsevolod Tolstopyatov <qwwdfsad@gmail.com>
152 files changed
tree: 05949893d311f8ba6bfacdb08a8570f57357a8b4
  1. .github/
  2. .idea/
  3. benchmark/
  4. docs/
  5. dokka/
  6. formats/
  7. gradle/
  8. guide/
  9. integration-test/
  10. license/
  11. runtime/
  12. .gitignore
  13. build.gradle
  14. CHANGELOG.md
  15. CODE_OF_CONDUCT.md
  16. CONTRIBUTING.md
  17. gradle.properties
  18. gradlew
  19. gradlew.bat
  20. knit.properties
  21. LICENSE.txt
  22. README.md
  23. RELEASING.md
  24. settings.gradle
  25. update_docs.sh
README.md

Kotlin multiplatform / multi-format reflectionless serialization

official JetBrains project GitHub license TeamCity build Download

Kotlin serialization consists of a compiler plugin, that generates visitor code for serializable classes, runtime libraries with core serialization API and JSON format, and support libraries with ProtoBuf, CBOR and properties formats.

  • Supports Kotlin classes marked as @Serializable and standard collections.
  • Provides JSON (as a part of the core library), Protobuf, CBOR, Hocon and Properties formats.
  • Complete multiplatform support: JVM, JS and Native.

Table of contents

Introduction and references

Here is a small example.

import kotlinx.serialization.*
import kotlinx.serialization.json.*

@Serializable 
data class Project(val name: String, val language: String)

fun main() {
    // Serializing objects
    val data = Project("kotlinx.serialization", "Kotlin")
    val string = Json.encodeToString(data)  
    println(string) // {"name":"kotlinx.serialization","language":"Kotlin"} 
    // Deserializing back into objects
    val obj = Json.decodeFromString<Project>(string)
    println(obj) // Project(name=kotlinx.serialization, langauge=Kotlin)
}

You can get the full code here.

Read the Kotlin Serialization Guide for all details.

Setup

Kotlin serialization plugin is shipped with the Kotlin compiler distribution, and the IDEA plugin is bundled into the Kotlin plugin.

Using Kotlin Serialization requires Kotlin compiler 1.4.0 or higher. Make sure you have the corresponding Kotlin plugin installed in the IDE, no additional plugins for IDE are required. Example projects on JVM are available for Gradle and Maven.

Gradle

Using the plugins block

You can set up the serialization plugin with the Kotlin plugin using Gradle plugins DSL:

Kotlin DSL:

plugins {
    kotlin("jvm") version "1.4.0" // or kotlin("multiplatform") or any other kotlin plugin
    kotlin("plugin.serialization") version "1.4.0"
}

Groovy DSL:

plugins {
    id 'org.jetbrains.kotlin.multiplatform' version '1.4.0'
    id 'org.jetbrains.kotlin.plugin.serialization' version '1.4.0'
}

Kotlin versions before are not supported by the stable release of Kotlin serialization

Using apply plugin (the old way)

First, you have to add the serialization plugin to your classpath as the other compiler plugins:

Kotlin DSL:

buildscript {
    repositories { jcenter() }

    dependencies {
        val kotlinVersion = "1.4.0"
        classpath(kotlin("gradle-plugin", version = kotlinVersion))
        classpath(kotlin("serialization", version = kotlinVersion))
    }
}

Groovy DSL:

buildscript {
    ext.kotlin_version = '1.4.0'
    repositories { jcenter() }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
    }
}

Then you can apply plugin (example in Groovy):

apply plugin: 'kotlin' // or 'kotlin-multiplatform' for multiplatform projects
apply plugin: 'kotlinx-serialization'

Dependency on the runtime library

After setting up the plugin one way or another, you have to add a dependency on the serialization runtime library. Note that while the plugin has version the same as the compiler one, runtime library has different coordinates, repository and versioning.

Kotlin DSL:

repositories {
    // artifacts are published to JCenter
    jcenter()
}

dependencies {
    implementation(kotlin("stdlib", KotlinCompilerVersion.VERSION)) // or "stdlib-jdk8"
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:1.0.0-RC") // JVM dependency
}

Groovy DSL:

repositories {
    jcenter()
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" // or "kotlin-stdlib-jdk8"
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-core:1.0.0-RC" // JVM dependency
}

Android/JVM

Library should work on Android "as is". If you're using proguard, you need to add this to your proguard-rules.pro:

-keepattributes *Annotation*, InnerClasses
-dontnote kotlinx.serialization.SerializationKt
-keep,includedescriptorclasses class com.yourcompany.yourpackage.**$$serializer { *; } # <-- change package name to your app's
-keepclassmembers class com.yourcompany.yourpackage.** { # <-- change package name to your app's
    *** Companion;
}
-keepclasseswithmembers class com.yourcompany.yourpackage.** { # <-- change package name to your app's
    kotlinx.serialization.KSerializer serializer(...);
}

You may also want to keep all custom serializers you've defined.

Multiplatform (common, JS, Native)

Typically, you need the following dependencies in your multiplatform project (don't forget to rename source sets according to your setup):

sourceSets {
    commonMain {
        dependencies {
            implementation kotlin('stdlib-common')
            implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:$serialization_version"
        }
    }
    commonTest {
        dependencies {
            implementation kotlin('test-common')
            implementation kotlin('test-annotations-common')
        }
    }
    jvmMain {
        dependencies {
            implementation kotlin('stdlib-jdk8')
        }
    }
    jvmTest {
        dependencies {
            implementation kotlin('test')
            implementation kotlin('test-junit')
        }
    }
    jsMain {
        dependencies {
            implementation kotlin('stdlib-js')
        }
    }
    jsTest {
        dependencies {
            implementation kotlin('test-js')
        }
    }
    nativeMain {}
    nativeTest {}
}

Maven/JVM

Ensure the proper version of Kotlin and serialization version:

<properties>
    <kotlin.version>1.4.0</kotlin.version>
    <serialization.version>1.0.0-RC</serialization.version>
</properties>

You can also use JCenter or https://kotlin.bintray.com/kotlinx Bintray repository.

Add serialization plugin to Kotlin compiler plugin:

<build>
    <plugins>
        <plugin>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-maven-plugin</artifactId>
            <version>${kotlin.version}</version>
            <executions>
                <execution>
                    <id>compile</id>
                    <phase>compile</phase>
                    <goals>
                        <goal>compile</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <compilerPlugins>
                    <plugin>kotlinx-serialization</plugin>
                </compilerPlugins>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.jetbrains.kotlin</groupId>
                    <artifactId>kotlin-maven-serialization</artifactId>
                    <version>${kotlin.version}</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

Add dependency on serialization runtime library:

<dependency>
    <groupId>org.jetbrains.kotlinx</groupId>
    <artifactId>kotlinx-serialization-core</artifactId>
    <version>${serialization.version}</version>
</dependency>