Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Kotlin multiplatform / multi-format serialization

License

NotificationsYou must be signed in to change notification settings

Kotlin/kotlinx.serialization

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Kotlin StableJetBrains official projectGitHub licenseTeamCity buildKotlinMaven CentralKDoc linkSlack channel

Kotlin serialization consists of a compiler plugin, that generates visitor code for serializable classes,runtime library with core serialization API and support libraries with various serialization formats.

  • Supports Kotlin classes marked as@Serializable and standard collections.
  • ProvidesJSON,Protobuf,CBOR,Hocon andProperties formats.
  • Complete multiplatform support: JVM, JS and Native.

Table of contents

Introduction and references

Here is a small example.

importkotlinx.serialization.*importkotlinx.serialization.json.*@Serializabledata classProject(valname:String,vallanguage:String)funmain() {// Serializing objectsval data=Project("kotlinx.serialization","Kotlin")val string=Json.encodeToString(data)println(string)// {"name":"kotlinx.serialization","language":"Kotlin"}// Deserializing back into objectsval obj=Json.decodeFromString<Project>(string)println(obj)// Project(name=kotlinx.serialization, language=Kotlin)}

You can get the full codehere.

Read theKotlin Serialization Guide for all details.

You can find auto-generated documentation website onkotlinlang.org.

Setup

New versions of the serialization plugin are released in tandem with each new Kotlin compiler version.

Make sure you have the corresponding Kotlin plugin installed in the IDE, no additional plugins for IDE are required.

Gradle

To set up kotlinx.serialization, you have to do two things:

  1. Add theserialization plugin.
  2. Add theserialization library dependency.

1) Setting up the serialization plugin

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

Kotlin DSL:

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

Groovy DSL:

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

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

Usingapply plugin (the old way)

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

Kotlin DSL:

buildscript {    repositories { mavenCentral() }    dependencies {val kotlinVersion="2.2.0"        classpath(kotlin("gradle-plugin", version= kotlinVersion))        classpath(kotlin("serialization", version= kotlinVersion))    }}

Groovy DSL:

buildscript {    ext.kotlin_version='2.2.0'    repositories { mavenCentral() }    dependencies {        classpath"org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"    }}

Then you canapply plugin (example in Groovy):

applyplugin:'kotlin'// or 'kotlin-multiplatform' for multiplatform projectsapplyplugin:'kotlinx-serialization'

2) Dependency on the JSON library

After setting up the plugin, you have to add a dependency on the serialization 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 {    mavenCentral()}dependencies {    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0")}

Groovy DSL:

repositories {    mavenCentral()}dependencies {    implementation"org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0"}

We also providekotlinx-serialization-core artifact that contains all serialization API but does not have a bundled serialization format with it

Android

By default, proguard rules are supplied with the library.These rules keep serializers forall serializable classes that are retained after shrinking,so you don't need additional setup.

However, these rules do not affect serializable classes if they have named companion objects.

If you want to serialize classes with named companion objects, you need to add and edit rules below to yourproguard-rules.pro configuration.

Note that the rules for R8 differ depending on thecompatibility mode used.

Example of named companion rules for ProGuard and R8 compatibility mode
# Serializer for classes with named companion objects are retrieved using `getDeclaredClasses`.# If you have any, replace classes with those containing named companion objects.-keepattributes InnerClasses # Needed for `getDeclaredClasses`.-if @kotlinx.serialization.Serializable classcom.example.myapplication.HasNamedCompanion, # <-- List serializable classes with named companions.com.example.myapplication.HasNamedCompanion2{    static **$* *;}-keepnames class <1>$$serializer { # -keepnames suffices; class is kept when serializer() is kept.    static <1>$$serializer INSTANCE;}
Example of named companion rules for R8 full mode
# Serializer for classes with named companion objects are retrieved using `getDeclaredClasses`.# If you have any, replace classes with those containing named companion objects.-keepattributes InnerClasses # Needed for `getDeclaredClasses`.-if @kotlinx.serialization.Serializable classcom.example.myapplication.HasNamedCompanion, # <-- List serializable classes with named companions.com.example.myapplication.HasNamedCompanion2{    static **$* *;}-keepnames class <1>$$serializer { # -keepnames suffices; 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 classcom.example.myapplication.HasNamedCompanion, # <-- List serializable classes with named companions.com.example.myapplication.HasNamedCompanion2{    *;}

In case you want to exclude serializable classes that are used, but never serialized at runtime,you will need to write custom rules with narrowerclass specifications.

Multiplatform (Common, JS, Native)

Most of the modules are also available for Kotlin/JS and Kotlin/Native.You can add dependency to the required module right to the common source set:

commonMain {    dependencies {// Works as common dependency as well as the platform one        implementation"org.jetbrains.kotlinx:kotlinx-serialization-json:$serialization_version"    }}

The same artifact coordinates can be used to depend on platform-specific artifact in platform-specific source-set.

Maven

Ensure the proper version of Kotlin and serialization version:

<properties>    <kotlin.version>2.2.0</kotlin.version>    <serialization.version>1.9.0</serialization.version></properties>

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-json</artifactId>    <version>${serialization.version}</version></dependency>

Bazel

To setup the Kotlin compiler plugin for Bazel, followtheexamplefrom therules_kotlin repository.

About

Kotlin multiplatform / multi-format serialization

Topics

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks


[8]ページ先頭

©2009-2025 Movatter.jp