From e7ef54f80ad8fcf527c9f7c1b5ac4660fa6e4f1d Mon Sep 17 00:00:00 2001 From: Daniel Csorba Date: Mon, 11 Aug 2025 13:37:13 +0200 Subject: [PATCH 1/4] feat: adding the get started page --- .../topics/serialization-get-started.md | 232 ++++++++++++++++++ 1 file changed, 232 insertions(+) create mode 100644 docs-website/topics/serialization-get-started.md diff --git a/docs-website/topics/serialization-get-started.md b/docs-website/topics/serialization-get-started.md new file mode 100644 index 000000000..204939a2b --- /dev/null +++ b/docs-website/topics/serialization-get-started.md @@ -0,0 +1,232 @@ +[//]: # (title: Get started with Kotlin serialization) + +[Serialization](serialization.md) converts objects into a format that can be stored or transmitted and later reconstructed. + +This tutorial shows you how to add the necessary plugins and dependencies for Kotlin serialization and how to serialize and deserialize objects in JSON format. + +## Add plugins and dependencies for Kotlin serialization + +To include the `kotlinx.serialization` library in your project, add the corresponding plugin and dependency configuration based on your build tool. + +> To set up the Kotlin compiler plugin for Bazel, see the example provided in the [rules_kotlin repository](https://github.com/bazelbuild/rules_kotlin/tree/master/examples/plugin/src/serialization). +> +{style="tip"} + +### Gradle + +Add the following dependency to your `build.gradle(.kts)` file: + + + + +```kotlin +// build.gradle.kts +plugins { + kotlin("plugin.serialization") version "%kotlinVersion%" +} + +dependencies { + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:%serializationVersion%") +} +``` + + + + + +```groovy +// build.gradle +plugins { + id 'org.jetbrains.kotlin.plugin.serialization' version '%kotlinVersion%' +} + +dependencies { + implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:%serializationVersion%' +} +``` + + + + + +### Maven + +Add the serialization plugin and library to your `pom.xml` file: + +1. Specify the Kotlin and serialization version in the `` section: + + ```xml + + %kotlinVersion% + %serializationVersion% + + ``` + +2. Add the Kotlin serialization Maven plugin to the `` section: + + ```xml + + + + org.jetbrains.kotlin + kotlin-maven-plugin + ${kotlin.version} + + + compile + compile + + compile + + + + + + kotlinx-serialization + + + + + org.jetbrains.kotlin + kotlin-maven-serialization + ${kotlin.version} + + + + + + ``` + +3. Add the JSON serialization library dependency to the `` section: + + ```xml + + + org.jetbrains.kotlinx + kotlinx-serialization-json + ${serialization.version} + + + ``` + +### Add the Kotlin serialization library to a multiplatform project + +To use Kotlin serialization in multiplatform projects, add the JSON serialization library dependency to your common source set: + +```kotlin +commonMain { + dependencies { + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:%serializationVersion%") + } +} +``` + +## Serialize objects to JSON + +Serialization is the process of converting an object into a format that can be easily stored or transmitted, such as JSON. +In Kotlin, you can serialize objects to JSON using the `kotlinx.serialization` library. + +To make a class serializable, you need to mark it with the [`@Serializable`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization/-serializable/) annotation. +This annotation instructs the compiler to generate the code required for serializing and deserializing instances of the class. +For more information, see [The @Serialization annotation](serialization-customization-options.md#the-serializable-annotation). + +Let's look at an example: + +1. Import the necessary serialization libraries: + + ```kotlin + import kotlinx.serialization.* + import kotlinx.serialization.json.* + ``` + +2. Make a class serializable by annotating it with `@Serializable`: + + ```kotlin + @Serializable + data class Data(val a: Int, val b: String) + ``` + + > The `@Serializable` annotation enables default serialization of all properties in the primary constructor. + > You can customize serialization behavior with custom constructors, optional properties, and more. + > + > For more information, see [Serialize classes](serialization-customization-options.md). + > + {style="note"} + +3. Use the [`Json.encodeToString()`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json/encode-to-string.html) function to serialize an instance of this class: + + ```kotlin + // Imports the necessary libraries for serialization and JSON handling + import kotlinx.serialization.* + import kotlinx.serialization.json.* + + // Marks the Data class as serializable + @Serializable + data class Data(val a: Int, val b: String) + + fun main() { + // Serializes an instance of the Data class into a JSON string + val json = Json.encodeToString(Data(42, "str")) + println(json) + // {"a":42,"b":"str"} + } + ``` + {kotlin-runnable="true"} + + As a result, you get a string containing the state of this object in JSON format: `{"a":42,"b":"str"}` + + > You can also serialize a collection of objects in a single call: + > + > ```kotlin + > val dataList = listOf(Data(42, "str"), Data(12, "test")) + > val jsonList = Json.encodeToString(dataList) + > ``` + > + {style="tip"} + +## Deserialize objects from JSON + +Deserialization converts a JSON string back into an object. + +To deserialize an object from JSON in Kotlin: + +1. Import the necessary serialization libraries: + + ```kotlin + import kotlinx.serialization.* + import kotlinx.serialization.json.* + ``` + +2. Make a class serializable by annotating it with `@Serializable`: + + ```kotlin + @Serializable + data class Data(val a: Int, val b: String) + ``` + +3. Use the [`Json.decodeFromString()`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json/decode-from-string.html) function to deserialize an object from JSON: + + ```kotlin + // Imports the necessary libraries for serialization and JSON handling + import kotlinx.serialization.* + import kotlinx.serialization.json.* + + // Marks the Data class as serializable + @Serializable + data class Data(val a: Int, val b: String) + + fun main() { + // Deserializes a JSON string into an instance of the Data class + val obj = Json.decodeFromString("""{"a":42, "b": "str"}""") + println(obj) + // Data(a=42, b=str) + } + ``` + {kotlin-runnable="true"} + +Congratulations! You have successfully serialized an object to JSON and deserialized it back into an object in Kotlin! + +## What's next +* Learn how to serialize standard types, including built-in types like numbers and strings, in [Serialize built-in types](serialization-serialize-builtin-types.md). +* Discover how to customize class serialization and adjust the default behavior of the `@Serializable` annotation in the [Serialize classes](serialization-customization-options.md) section. +* Dive deeper into handling JSON data and configuring JSON serialization in the [JSON serialization overview](configure-json-serialization.md). From c8e292062f88e265be720539e57745903649cee7 Mon Sep 17 00:00:00 2001 From: Daniel Csorba Date: Thu, 14 Aug 2025 17:06:48 +0200 Subject: [PATCH 2/4] implementing review comments from first round of review --- .../topics/serialization-get-started.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/docs-website/topics/serialization-get-started.md b/docs-website/topics/serialization-get-started.md index 204939a2b..b5f28f932 100644 --- a/docs-website/topics/serialization-get-started.md +++ b/docs-website/topics/serialization-get-started.md @@ -57,8 +57,8 @@ Add the serialization plugin and library to your `pom.xml` file: ```xml - %kotlinVersion% - %serializationVersion% + %kotlinVersion% + %serializationVersion% ``` @@ -123,7 +123,6 @@ commonMain { ## Serialize objects to JSON -Serialization is the process of converting an object into a format that can be easily stored or transmitted, such as JSON. In Kotlin, you can serialize objects to JSON using the `kotlinx.serialization` library. To make a class serializable, you need to mark it with the [`@Serializable`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization/-serializable/) annotation. @@ -132,7 +131,7 @@ For more information, see [The @Serialization annotation](serialization-customiz Let's look at an example: -1. Import the necessary serialization libraries: +1. Import declarations from the necessary serialization libraries: ```kotlin import kotlinx.serialization.* @@ -146,8 +145,8 @@ Let's look at an example: data class Data(val a: Int, val b: String) ``` - > The `@Serializable` annotation enables default serialization of all properties in the primary constructor. - > You can customize serialization behavior with custom constructors, optional properties, and more. + > The `@Serializable` annotation enables default serialization of all properties with backing fields. + > You can customize serialization behavior with property-level annotations, optional properties, and more. > > For more information, see [Serialize classes](serialization-customization-options.md). > @@ -156,7 +155,7 @@ Let's look at an example: 3. Use the [`Json.encodeToString()`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json/encode-to-string.html) function to serialize an instance of this class: ```kotlin - // Imports the necessary libraries for serialization and JSON handling + // Imports declarations from the serialization and JSON handling libraries import kotlinx.serialization.* import kotlinx.serialization.json.* @@ -190,7 +189,7 @@ Deserialization converts a JSON string back into an object. To deserialize an object from JSON in Kotlin: -1. Import the necessary serialization libraries: +1. Import declarations from the necessary serialization libraries: ```kotlin import kotlinx.serialization.* @@ -207,7 +206,7 @@ To deserialize an object from JSON in Kotlin: 3. Use the [`Json.decodeFromString()`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json/decode-from-string.html) function to deserialize an object from JSON: ```kotlin - // Imports the necessary libraries for serialization and JSON handling + // Imports declarations from the serialization and JSON handling libraries import kotlinx.serialization.* import kotlinx.serialization.json.* @@ -227,6 +226,7 @@ To deserialize an object from JSON in Kotlin: Congratulations! You have successfully serialized an object to JSON and deserialized it back into an object in Kotlin! ## What's next + * Learn how to serialize standard types, including built-in types like numbers and strings, in [Serialize built-in types](serialization-serialize-builtin-types.md). * Discover how to customize class serialization and adjust the default behavior of the `@Serializable` annotation in the [Serialize classes](serialization-customization-options.md) section. * Dive deeper into handling JSON data and configuring JSON serialization in the [JSON serialization overview](configure-json-serialization.md). From c31a5b7230ffff531fcc61c2689dbdaef9d3d9a9 Mon Sep 17 00:00:00 2001 From: Daniel Csorba Date: Fri, 17 Oct 2025 11:29:41 +0200 Subject: [PATCH 3/4] implementing second round of comments for the get started page --- .../topics/serialization-get-started.md | 194 +++++++++++------- 1 file changed, 121 insertions(+), 73 deletions(-) diff --git a/docs-website/topics/serialization-get-started.md b/docs-website/topics/serialization-get-started.md index b5f28f932..abb7e54b8 100644 --- a/docs-website/topics/serialization-get-started.md +++ b/docs-website/topics/serialization-get-started.md @@ -2,22 +2,15 @@ [Serialization](serialization.md) converts objects into a format that can be stored or transmitted and later reconstructed. +Kotlin serialization supports multiple formats. This tutorial shows you how to add the necessary plugins and dependencies for Kotlin serialization and how to serialize and deserialize objects in JSON format. -## Add plugins and dependencies for Kotlin serialization +## Add plugins and dependencies for Kotlin serialization to your project -To include the `kotlinx.serialization` library in your project, add the corresponding plugin and dependency configuration based on your build tool. - -> To set up the Kotlin compiler plugin for Bazel, see the example provided in the [rules_kotlin repository](https://github.com/bazelbuild/rules_kotlin/tree/master/examples/plugin/src/serialization). -> -{style="tip"} - -### Gradle - -Add the following dependency to your `build.gradle(.kts)` file: +To include the `kotlinx.serialization` library in your project, add the corresponding plugin and dependency configuration based on your build tool: - + ```kotlin // build.gradle.kts @@ -31,8 +24,7 @@ dependencies { ``` - - + ```groovy // build.gradle @@ -46,72 +38,65 @@ dependencies { ``` + + +```xml + + + %kotlinVersion% + %serializationVersion% + + + + + + org.jetbrains.kotlin + kotlin-maven-plugin + ${kotlin.version} + + + compile + compile + + compile + + + + + + kotlinx-serialization + + + + + org.jetbrains.kotlin + kotlin-maven-serialization + ${kotlin.version} + + + + + + + + + org.jetbrains.kotlinx + kotlinx-serialization-json + ${serialization.version} + + +``` + -### Maven - -Add the serialization plugin and library to your `pom.xml` file: - -1. Specify the Kotlin and serialization version in the `` section: - - ```xml - - %kotlinVersion% - %serializationVersion% - - ``` - -2. Add the Kotlin serialization Maven plugin to the `` section: - - ```xml - - - - org.jetbrains.kotlin - kotlin-maven-plugin - ${kotlin.version} - - - compile - compile - - compile - - - - - - kotlinx-serialization - - - - - org.jetbrains.kotlin - kotlin-maven-serialization - ${kotlin.version} - - - - - - ``` - -3. Add the JSON serialization library dependency to the `` section: - - ```xml - - - org.jetbrains.kotlinx - kotlinx-serialization-json - ${serialization.version} - - - ``` +> To set up the Kotlin compiler plugin for Bazel, see the example provided in the [rules_kotlin repository](https://github.com/bazelbuild/rules_kotlin/tree/master/examples/plugin/src/serialization). +> +{style="tip"} ### Add the Kotlin serialization library to a multiplatform project -To use Kotlin serialization in multiplatform projects, add the JSON serialization library dependency to your common source set: +To use Kotlin serialization for JSON in multiplatform projects, add the JSON serialization library dependency to your common source set: ```kotlin commonMain { @@ -121,6 +106,69 @@ commonMain { } ``` +This dependency automatically includes the core serialization library as well. + +### Configure R8 for Kotlin serialization in Android projects {initial-collapse-state="collapsed" collapsible="true"} + +The Kotlin serialization library includes default [ProGuard rules](https://github.com/Kotlin/kotlinx.serialization/blob/master/rules/common.pro) that keep serializers for all serializable classes retained after shrinking. +These rules don't apply to classes with named companion objects. + +To retain serializers for classes with named companion objects, add rules based on the [compatibility mode](https://r8.googlesource.com/r8/+/refs/heads/master/compatibility-faq.md) you use to your `proguard-rules.pro` file: + + + + +```bash +# Serializer for classes with named companion objects are retrieved using getDeclaredClasses +# If you have any such classes, replace the examples below with your own +-keepattributes InnerClasses # Required for getDeclaredClasses + +-if @kotlinx.serialization.Serializable class +com.example.myapplication.HasNamedCompanion, # <-- List serializable classes with named companions +com.example.myapplication.HasNamedCompanion2 +{ + static **$* *; +} +-keepnames class <1>$$serializer { # Using -keepnames is enough; class is kept when serializer() is kept + static <1>$$serializer INSTANCE; +} +``` + + + + + +```bash +# Serializer for classes with named companion objects are retrieved using getDeclaredClasses +# If you have any such classes, replace the examples below with your own +-keepattributes InnerClasses # Required for getDeclaredClasses + +-if @kotlinx.serialization.Serializable class +com.example.myapplication.HasNamedCompanion, # <-- List serializable classes with named companions +com.example.myapplication.HasNamedCompanion2 +{ + static **$* *; +} +-keepnames class <1>$$serializer { # Using -keepnames is enough; class is kept when serializer() is kept + static <1>$$serializer INSTANCE; +} + +# Keep both serializer and serializable classes to save the attribute InnerClasses +-keepclasseswithmembers, allowshrinking, allowobfuscation, allowaccessmodification class +com.example.myapplication.HasNamedCompanion, # <-- List serializable classes with named companions +com.example.myapplication.HasNamedCompanion2 +{ + *; +} +``` + + + + +> You can exclude serializable classes that are never serialized at runtime by using custom ProGuard rules with narrower [class specifications](https://www.guardsquare.com/manual/configuration/usage). +> +{style="tip"} + ## Serialize objects to JSON In Kotlin, you can serialize objects to JSON using the `kotlinx.serialization` library. From 537ff6b459d74e5ea7229e348a381144e39af6dc Mon Sep 17 00:00:00 2001 From: Daniel Csorba Date: Fri, 17 Oct 2025 11:33:02 +0200 Subject: [PATCH 4/4] fix: using slightly smoother wording for R8 --- docs-website/topics/serialization-get-started.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs-website/topics/serialization-get-started.md b/docs-website/topics/serialization-get-started.md index abb7e54b8..3168e673b 100644 --- a/docs-website/topics/serialization-get-started.md +++ b/docs-website/topics/serialization-get-started.md @@ -110,7 +110,7 @@ This dependency automatically includes the core serialization library as well. ### Configure R8 for Kotlin serialization in Android projects {initial-collapse-state="collapsed" collapsible="true"} -The Kotlin serialization library includes default [ProGuard rules](https://github.com/Kotlin/kotlinx.serialization/blob/master/rules/common.pro) that keep serializers for all serializable classes retained after shrinking. +The Kotlin serialization library includes default [ProGuard rules](https://github.com/Kotlin/kotlinx.serialization/blob/master/rules/common.pro) to keep serializers for all serializable classes after shrinking. These rules don't apply to classes with named companion objects. To retain serializers for classes with named companion objects, add rules based on the [compatibility mode](https://r8.googlesource.com/r8/+/refs/heads/master/compatibility-faq.md) you use to your `proguard-rules.pro` file: