-
Notifications
You must be signed in to change notification settings - Fork 662
Documentation rewrite - Get started page #3059
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: doc-restructuring-master
Are you sure you want to change the base?
Changes from all commits
e7ef54f
c8e2920
c31a5b7
537ff6b
68f4be6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,281 @@ | ||||||
| [//]: # (title: Get started with Kotlin serialization) | ||||||
|
|
||||||
| [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. | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
|
|
||||||
daniCsorbaJB marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
| ## Add plugins and dependencies for Kotlin serialization to your project | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
I think we can shorten this since it's clear we're talking about the Kotlin serialization library. |
||||||
|
|
||||||
| To include the `kotlinx.serialization` library in your project, add the corresponding plugin and dependency configuration based on your build tool: | ||||||
|
|
||||||
| <tabs> | ||||||
| <tab id="kotlin" title="Gradle Kotlin"> | ||||||
|
|
||||||
| ```kotlin | ||||||
| // build.gradle.kts | ||||||
| plugins { | ||||||
| kotlin("plugin.serialization") version "%kotlinVersion%" | ||||||
| } | ||||||
|
|
||||||
| dependencies { | ||||||
| implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:%serializationVersion%") | ||||||
| } | ||||||
| ``` | ||||||
|
|
||||||
| </tab> | ||||||
| <tab id="groovy" title="Gradle Groovy"> | ||||||
|
|
||||||
| ```groovy | ||||||
| // build.gradle | ||||||
| plugins { | ||||||
| id 'org.jetbrains.kotlin.plugin.serialization' version '%kotlinVersion%' | ||||||
| } | ||||||
|
|
||||||
| dependencies { | ||||||
| implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:%serializationVersion%' | ||||||
| } | ||||||
| ``` | ||||||
|
|
||||||
| </tab> | ||||||
| <tab id="maven" title="Maven"> | ||||||
|
|
||||||
| ```xml | ||||||
| <!-- pom.xml --> | ||||||
| <properties> | ||||||
| <kotlin.version>%kotlinVersion%</kotlin.version> | ||||||
| <serialization.version>%serializationVersion%</serialization.version> | ||||||
| </properties> | ||||||
|
|
||||||
| <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> | ||||||
|
|
||||||
| <dependencies> | ||||||
| <dependency> | ||||||
| <groupId>org.jetbrains.kotlinx</groupId> | ||||||
| <artifactId>kotlinx-serialization-json</artifactId> | ||||||
| <version>${serialization.version}</version> | ||||||
| </dependency> | ||||||
| </dependencies> | ||||||
| ``` | ||||||
|
|
||||||
| </tab> | ||||||
| </tabs> | ||||||
|
|
||||||
| > To set up the Kotlin compiler plugin for Bazel, follow the example from the [rules_kotlin repository](https://github.com/bazelbuild/rules_kotlin/tree/master/examples/plugin/src/serialization). | ||||||
| > Bazel isn't officially supported by the Kotlin team, and this repository is maintained independently. | ||||||
| > | ||||||
| {style="tip"} | ||||||
|
|
||||||
| ### Add the Kotlin serialization library to a multiplatform project | ||||||
daniCsorbaJB marked this conversation as resolved.
Show resolved
Hide resolved
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
|
|
||||||
| To use Kotlin serialization for JSON 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%") | ||||||
| } | ||||||
| } | ||||||
| ``` | ||||||
|
|
||||||
| 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), so you don't need additional setup to keep serializers for all serializable classes after shrinking. | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Would it be possible to briefly explain what R8 is for the readers who aren't Android developers? Maybe linking to https://developer.android.com/topic/performance/app-optimization/enable-app-optimization? |
||||||
| These rules don't apply to classes with named companion objects. | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
|
|
||||||
| 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: | ||||||
|
|
||||||
| <tabs> | ||||||
| <tab id="compatibility" title="R8 compatibility mode"> | ||||||
|
|
||||||
| ```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 | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm not sure what the part after the semi-colon means? |
||||||
| static <1>$$serializer INSTANCE; | ||||||
| } | ||||||
| ``` | ||||||
|
|
||||||
| </tab> | ||||||
|
|
||||||
| <tab id="full" title="R8 full mode"> | ||||||
|
|
||||||
| ```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 | ||||||
| { | ||||||
| *; | ||||||
| } | ||||||
| ``` | ||||||
|
|
||||||
| </tab> | ||||||
| </tabs> | ||||||
|
|
||||||
| > 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. | ||||||
|
|
||||||
| 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. | ||||||
daniCsorbaJB marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
| 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). | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||||||
|
|
||||||
| Let's look at an example: | ||||||
|
|
||||||
| 1. Import declarations from 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) | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could you improve the example by making it more real world like? For example, the data class could be called |
||||||
| ``` | ||||||
|
|
||||||
| > 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). | ||||||
| > | ||||||
| {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 declarations from the serialization and JSON handling libraries | ||||||
| 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"} | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can you give it an ID so we can see how many people run it in GA? |
||||||
|
|
||||||
| 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 declarations from 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 declarations from the serialization and JSON handling libraries | ||||||
| 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<Data>("""{"a":42, "b": "str"}""") | ||||||
| println(obj) | ||||||
| // Data(a=42, b=str) | ||||||
| } | ||||||
| ``` | ||||||
| {kotlin-runnable="true"} | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It would also be great to have an ID here. |
||||||
|
|
||||||
| Congratulations! You have successfully serialized an object to JSON and deserialized it back into an object in Kotlin! | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
Nitpick. Just to make it sound not so excitable :) |
||||||
|
|
||||||
| ## What's next | ||||||
sandwwraith marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
|
|
||||||
| * Learn how to serialize standard types, including built-in types like numbers and strings, in [Serialize built-in types](serialization-serialize-builtin-types.md). | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. By "standard" do you mean basic types? |
||||||
| * Discover how to customize class serialization and adjust the default behavior of the `@Serializable` annotation in the [Serialize classes](serialization-customization-options.md) section. | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Will it be a section in this page? Or is it a page itself? |
||||||
| * Dive deeper into handling JSON data and configuring JSON serialization in the [JSON serialization overview](configure-json-serialization.md). | ||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What do you think about making this more active?