Kotlinx.serialization - Kotlin multiplatform / multi-format reflectionless serialization

Overview

Kotlin multiplatform / multi-format reflectionless serialization

official JetBrains project GitHub license TeamCity build Kotlin Maven Central KDoc link Slack 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.
  • Provides JSON, Protobuf, CBOR, Hocon and Properties formats.
  • Complete multiplatform support: JVM, JS and Native.

Table of contents

Introduction and references

Here is a small example.

(string) println(obj) // Project(name=kotlinx.serialization, language=Kotlin) }">
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, language=Kotlin)
}

You can get the full code here.

Read the Kotlin Serialization Guide for all details.

You can find auto-generated documentation website on GitHub Pages.

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.

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.6.10" // or kotlin("multiplatform") or any other kotlin plugin
    kotlin("plugin.serialization") version "1.6.10"
}

Groovy DSL:

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

Kotlin versions before 1.4.0 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 { mavenCentral() }

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

Groovy DSL:

buildscript {
    ext.kotlin_version = '1.6.10'
    repositories { mavenCentral() }

    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 JSON library

After setting up the plugin one way or another, 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.3.2")
}

Groovy DSL:

repositories {
    mavenCentral()
}

dependencies {
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.2"
}

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

Android

The library works on Android, but, if you're using ProGuard, you need to add rules to your proguard-rules.pro configuration to cover all classes that are serialized at runtime.

The following configuration keeps serializers for all serializable classes that are retained after shrinking. Uncomment and modify the last section in case you're serializing classes with named companion objects.

# Keep `Companion` object fields of serializable classes.
# This avoids serializer lookup through `getDeclaredClasses` as done for named companion objects.
-if @kotlinx.serialization.Serializable class **
-keepclassmembers class <1> {
    static <1>$Companion Companion;
}

# Keep `serializer()` on companion objects (both default and named) of serializable classes.
-if @kotlinx.serialization.Serializable class ** {
    static **$* *;
}
-keepclassmembers class <1>$<3> {
    kotlinx.serialization.KSerializer serializer(...);
}

# Keep `INSTANCE.serializer()` of serializable objects.
-if @kotlinx.serialization.Serializable class ** {
    public static ** INSTANCE;
}
-keepclassmembers class <1> {
    public static <1> INSTANCE;
    kotlinx.serialization.KSerializer serializer(...);
}

# @Serializable and @Polymorphic are used at runtime for polymorphic serialization.
-keepattributes RuntimeVisibleAnnotations,AnnotationDefault

# Serializer for classes with named companion objects are retrieved using `getDeclaredClasses`.
# If you have any, uncomment and replace classes with those containing named companion objects.
#-keepattributes InnerClasses # Needed 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 { # -keepnames suffices; class is kept when serializer() is kept.
#    static <1>$$serializer INSTANCE;
#}

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

Example of custom rules
-keepattributes RuntimeVisibleAnnotations,AnnotationDefault

# kotlinx-serialization-json specific. Add this if you have java.lang.NoClassDefFoundError kotlinx.serialization.json.JsonObjectSerializer
-keepclassmembers class kotlinx.serialization.json.** {
    *** Companion;
}
-keepclasseswithmembers class kotlinx.serialization.json.** {
    kotlinx.serialization.KSerializer serializer(...);
}

# Application rules

# Change here com.yourcompany.yourpackage
-keepclassmembers @kotlinx.serialization.Serializable class com.yourcompany.yourpackage.** {
    # lookup for plugin generated serializable classes
    *** Companion;
    # lookup for serializable objects
    *** INSTANCE;
    kotlinx.serialization.KSerializer serializer(...);
}
# lookup for plugin generated serializable classes
-if @kotlinx.serialization.Serializable class com.yourcompany.yourpackage.**
-keepclassmembers class com.yourcompany.yourpackage.<1>$Companion {
    kotlinx.serialization.KSerializer serializer(...);
}

# Serialization supports named companions but for such classes it is necessary to add an additional rule.
# This rule keeps serializer and serializable class from obfuscation. Therefore, it is recommended not to use wildcards in it, but to write rules for each such class.
-keepattributes InnerClasses # Needed for `getDeclaredClasses`.
-keep class com.yourcompany.yourpackage.SerializableClassWithNamedCompanion$$serializer {
    *** INSTANCE;
}

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>1.6.10kotlin.version>
    <serialization.version>1.3.2serialization.version>
properties>

Add serialization plugin to Kotlin compiler plugin:

<build>
    <plugins>
        <plugin>
            <groupId>org.jetbrains.kotlingroupId>
            <artifactId>kotlin-maven-pluginartifactId>
            <version>${kotlin.version}version>
            <executions>
                <execution>
                    <id>compileid>
                    <phase>compilephase>
                    <goals>
                        <goal>compilegoal>
                    goals>
                execution>
            executions>
            <configuration>
                <compilerPlugins>
                    <plugin>kotlinx-serializationplugin>
                compilerPlugins>
            configuration>
            <dependencies>
                <dependency>
                    <groupId>org.jetbrains.kotlingroupId>
                    <artifactId>kotlin-maven-serializationartifactId>
                    <version>${kotlin.version}version>
                dependency>
            dependencies>
        plugin>
    plugins>
build>

Add dependency on serialization runtime library:

<dependency>
    <groupId>org.jetbrains.kotlinxgroupId>
    <artifactId>kotlinx-serialization-jsonartifactId>
    <version>${serialization.version}version>
dependency>
Comments
  • IntelliJ Idea: Unresolved reference: serializer

    IntelliJ Idea: Unresolved reference: serializer

    Idea doesn't compile project files with an error: "Kotlin: Unresolved reference: serializer". I tried various cleanup task and IDE restarting and a project reimport but it doesn't solve the issue.

    Meantime gradle itself works perfectly without any errors.

    build.gradle.kts

    buildscript {
      repositories { jcenter() }
    
      dependencies {
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.0")
        classpath("org.jetbrains.kotlin:kotlin-serialization:1.3.0")
      }
    }
    
    apply {
      plugin("kotlin")
      plugin("kotlinx-serialization")
      ...
    }
    
    dependencies {
      compile(kotlin("stdlib", "1.3.0"))
      compile("org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.9.0")
      ...
    }
    

    Idea version

    IntelliJ IDEA 2018.2.5 (Ultimate Edition)
    Build #IU-182.4892.20, built on October 16, 2018
    JRE: 1.8.0_152-release-1248-b19 x86_64
    JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
    macOS 10.14
    

    Idea kotlin plugin version:

    1.3.0-release-IJ2018.2-1
    
    opened by dmexe 36
  • How to convert map into json string

    How to convert map into json string

    example val params = mutableMapOf<String, Any>() params.put("long", 100L) params.put("int", 10) params.put("string", "haha") params.put("map", mutableMapOf("longg" to 10L, "stringg" to "ok")) LogUtil.d("test", json.stringify(params))

    question 
    opened by roths 31
  • Option to not write optional values

    Option to not write optional values

    Is it possible to add an option to not write optional values?

    For example, either if in nonstrict mode or add an parameter to @Optional. Something like:

    @Optional(dontwritewhen=2) val value: Int = 2

    or

    @Optional(writedefault=false) val value: Int = 2

    feature 
    opened by czeidler 31
  • SerializationComponentRegistrar is not compatible with this version of compiler (1.2.31?)

    SerializationComponentRegistrar is not compatible with this version of compiler (1.2.31?)

    Error:Kotlin: [Internal Error] java.lang.IllegalStateException: The provided plugin org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationComponentRegistrar is not compatible with this version of compiler at org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment.(KotlinCoreEnvironment.kt:178) at org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment.(KotlinCoreEnvironment.kt:114) at org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment$Companion.createForProduction(KotlinCoreEnvironment.kt:409) at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.createCoreEnvironment(K2JVMCompiler.kt:286) at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.createEnvironmentWithScriptingSupport(K2JVMCompiler.kt:276) at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:155) at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:63) at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:109) at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:53) at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:92) at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$$inlined$ifAlive$lambda$1.invoke(CompileServiceImpl.kt:381) at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$$inlined$ifAlive$lambda$1.invoke(CompileServiceImpl.kt:97) at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:895) at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:97) at org.jetbrains.kotlin.daemon.common.DummyProfiler.withMeasure(PerfUtils.kt:137) at org.jetbrains.kotlin.daemon.CompileServiceImpl.checkedCompile(CompileServiceImpl.kt:925) at org.jetbrains.kotlin.daemon.CompileServiceImpl.doCompile(CompileServiceImpl.kt:894) at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:379) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346) at sun.rmi.transport.Transport$1.run(Transport.java:200) at sun.rmi.transport.Transport$1.run(Transport.java:197) at java.security.AccessController.doPrivileged(Native Method) at sun.rmi.transport.Transport.serviceCall(Transport.java:196) at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568) at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826) at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683) at java.security.AccessController.doPrivileged(Native Method) at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:748) Caused by: java.lang.AbstractMethodError: org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationComponentRegistrar.registerProjectComponents(Lcom/intellij/mock/MockProject;Lorg/jetbrains/kotlin/config/CompilerConfiguration;)V at org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment.(KotlinCoreEnvironment.kt:176) ... 34 more

    opened by KucherenkoIhor 28
  • Node/NPM package available?

    Node/NPM package available?

    @sandwwraith I have a project generated by create-react-kotlin-app, so there is no gradle or maven build file, just a package.json.

    In my package.json, I have dependencies like:

      "dependencies": {
        "@jetbrains/kotlin-css": "^1.0.0-pre.48",
        "@jetbrains/kotlin-css-js": "^1.0.0-pre.48",
        "@jetbrains/kotlin-styled": "^1.0.0-pre.48",
        ...
      }
    

    While kotlinx.serialization purports to have JavaScript support, I am at a loss as to how to manage the dependency in a node/npm deployment ... in the absence of gradle or maven.

    Any ideas?

    question 
    opened by brettwooldridge 26
  • Enum class does not have .values() function when useIR = true

    Enum class does not have .values() function when useIR = true

    Describe the bug Project won't compile when using custom serializer for enums and when using useIR = true.

    e: java.lang.AssertionError: Enum class does not have .values() function
    	at org.jetbrains.kotlinx.serialization.compiler.backend.ir.IrBuilderExtension$DefaultImpls.findEnumValuesMethod(GeneratorHelpers.kt:458)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.ir.SerializerIrGenerator.findEnumValuesMethod(SerializerIrGenerator.kt:48)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.ir.IrBuilderExtension$DefaultImpls.serializerInstance(GeneratorHelpers.kt:666)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.ir.SerializerIrGenerator.serializerInstance(SerializerIrGenerator.kt:48)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.ir.IrBuilderExtension$serializerInstance$2.invoke(GeneratorHelpers.kt:567)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.ir.IrBuilderExtension$DefaultImpls.serializerInstance(GeneratorHelpers.kt:678)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.ir.SerializerIrGenerator.serializerInstance(SerializerIrGenerator.kt:48)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.ir.IrBuilderExtension$DefaultImpls.serializerInstance(GeneratorHelpers.kt:538)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.ir.SerializerIrGenerator.serializerInstance(SerializerIrGenerator.kt:48)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.ir.SerializerIrGenerator$generateSave$1.invoke(SerializerIrGenerator.kt:278)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.ir.SerializerIrGenerator$generateSave$1.invoke(SerializerIrGenerator.kt:48)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.ir.IrBuilderExtension$DefaultImpls.contributeFunction(GeneratorHelpers.kt:47)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.ir.SerializerIrGenerator.contributeFunction(SerializerIrGenerator.kt:48)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.ir.SerializerIrGenerator.generateSave(SerializerIrGenerator.kt:227)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.common.SerializerCodegen.generateSaveIfNeeded(SerializerCodegen.kt:105)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.common.SerializerCodegen.generate(SerializerCodegen.kt:34)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.ir.SerializerIrGenerator$Companion.generate(SerializerIrGenerator.kt:503)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializerClassLowering.lower(SerializationLoweringExtension.kt:48)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt$runOnFileInOrder$1.visitClass(SerializationLoweringExtension.kt:34)
    	at org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid$DefaultImpls.visitClass(IrElementVisitorVoid.kt:44)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt$runOnFileInOrder$1.visitClass(SerializationLoweringExtension.kt:28)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt$runOnFileInOrder$1.visitClass(SerializationLoweringExtension.kt:28)
    	at org.jetbrains.kotlin.ir.declarations.impl.IrClassImpl.accept(IrClassImpl.kt:166)
    	at org.jetbrains.kotlin.ir.declarations.impl.IrClassImpl.acceptChildren(IrClassImpl.kt:171)
    	at org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoidKt.acceptChildrenVoid(IrElementVisitorVoid.kt:275)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt$runOnFileInOrder$1.visitClass(SerializationLoweringExtension.kt:35)
    	at org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid$DefaultImpls.visitClass(IrElementVisitorVoid.kt:44)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt$runOnFileInOrder$1.visitClass(SerializationLoweringExtension.kt:28)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt$runOnFileInOrder$1.visitClass(SerializationLoweringExtension.kt:28)
    	at org.jetbrains.kotlin.ir.declarations.impl.IrClassImpl.accept(IrClassImpl.kt:166)
    	at org.jetbrains.kotlin.ir.declarations.impl.IrFileImpl.acceptChildren(IrFileImpl.kt:59)
    	at org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoidKt.acceptChildrenVoid(IrElementVisitorVoid.kt:275)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt$runOnFileInOrder$1.visitElement(SerializationLoweringExtension.kt:30)
    	at org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid$DefaultImpls.visitPackageFragment(IrElementVisitorVoid.kt:30)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt$runOnFileInOrder$1.visitPackageFragment(SerializationLoweringExtension.kt:28)
    	at org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid$DefaultImpls.visitFile(IrElementVisitorVoid.kt:37)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt$runOnFileInOrder$1.visitFile(SerializationLoweringExtension.kt:28)
    	at org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid$DefaultImpls.visitFile(IrElementVisitorVoid.kt:38)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt$runOnFileInOrder$1.visitFile(SerializationLoweringExtension.kt:28)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt$runOnFileInOrder$1.visitFile(SerializationLoweringExtension.kt:28)
    	at org.jetbrains.kotlin.ir.declarations.impl.IrFileImpl.accept(IrFileImpl.kt:56)
    	at org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoidKt.acceptVoid(IrElementVisitorVoid.kt:271)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt.runOnFileInOrder(SerializationLoweringExtension.kt:28)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtension.generate(SerializationLoweringExtension.kt:60)
    	at org.jetbrains.kotlin.backend.jvm.JvmBackendFacade$doGenerateFiles$1.invoke(JvmBackendFacade.kt:72)
    	at org.jetbrains.kotlin.backend.jvm.JvmBackendFacade$doGenerateFiles$1.invoke(JvmBackendFacade.kt:34)
    	at org.jetbrains.kotlin.psi2ir.Psi2IrTranslator.generateModuleFragment(Psi2IrTranslator.kt:98)
    	at org.jetbrains.kotlin.backend.jvm.JvmBackendFacade.doGenerateFiles(JvmBackendFacade.kt:87)
    	at org.jetbrains.kotlin.backend.jvm.JvmIrCodegenFactory.generateModule(JvmIrCodegenFactory.kt:40)
    	at org.jetbrains.kotlin.codegen.KotlinCodegenFacade.compileCorrectFiles(KotlinCodegenFacade.java:35)
    	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.generate(KotlinToJVMBytecodeCompiler.kt:616)
    	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:203)
    	at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:164)
    	at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:51)
    	at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:86)
    	at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:44)
    	at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:98)
    	at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:346)
    	at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:102)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compileIncrementally(IncrementalCompilerRunner.kt:240)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.access$compileIncrementally(IncrementalCompilerRunner.kt:39)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner$compile$2.invoke(IncrementalCompilerRunner.kt:81)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compile(IncrementalCompilerRunner.kt:93)
    	at org.jetbrains.kotlin.daemon.CompileServiceImplBase.execIncrementalCompiler(CompileServiceImpl.kt:601)
    	at org.jetbrains.kotlin.daemon.CompileServiceImplBase.access$execIncrementalCompiler(CompileServiceImpl.kt:93)
    	at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:1633)
    	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    	at java.rmi/sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:359)
    	at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:200)
    	at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:197)
    	at java.base/java.security.AccessController.doPrivileged(Native Method)
    	at java.rmi/sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    	at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:562)
    	at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:796)
    	at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:677)
    	at java.base/java.security.AccessController.doPrivileged(Native Method)
    	at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:676)
    	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    	at java.base/java.lang.Thread.run(Thread.java:834)
    

    To Reproduce Unable to reproduce with a clean project :(

    Expected behavior Should compile the same as with useIR = false

    Environment

    • Kotlin version: 1.4.0
    • Library version: 1.0.0-RC
    • Kotlin platforms: JVM
    • Gradle version: 6.6
    • IDE version (if bug is related to the IDE) IntellijIDEA 2020.2.1
    • Other relevant context
    openjdk version "11.0.7" 2020-04-14
    OpenJDK Runtime Environment GraalVM CE 20.1.0 (build 11.0.7+10-jvmci-20.1-b02)
    OpenJDK 64-Bit Server VM GraalVM CE 20.1.0 (build 11.0.7+10-jvmci-20.1-b02, mixed mode, sharing)
    
    bug compiler-plugin Priority: 3 
    opened by brezinajn 24
  • Regression when serialize  wrapped Any type property annotated with @Contextual

    Regression when serialize wrapped Any type property annotated with @Contextual

    Describe the bug Kotlin version: 1.4.0 + kotlinx-serialization-core:1.0.0-RC) + @Contextual val data: Any? reports:

    Exception in thread "main" kotlinx.serialization.SerializationException: Serializer for class 'Any' is not found.

    But when (Kotlin version: 1.3.70 + kotlinx-serialization-runtime:0.20.0), @ContextualSerialization val data: Any? works fine.

    To Reproduce

    @Serializable
    abstract class Box(
            var code: String,
            var msg: String?
    ){
        constructor(): this(OK, null)
        companion object{
            const val OK = "OK"
        }
    }
    
    @Serializable
    //data class DataBox(@ContextualSerialization val data: Any?) : Box(OK,null)  //kotlin 1.3.70
    data class DataBox(@Contextual val data: Any?) : Box(OK,null) //kotlin 1.4.0
    {
        constructor(): this(null)
    }
    
    fun test3(){
        val json = Json{}
        //val str = json.stringify(DataBox.serializer(),DataBox(data = Person("Tom"))) //kotlin 1.3.70, ouput: {"code":"OK","msg":null,"data":{"name":"Tom"}}
        val str = json.encodeToString(DataBox.serializer(),DataBox(data = Person("Tom")))// kotlin 1.4.0: Execption!!! 
        println(str)
    }
    

    reports error:

    Exception in thread "main" kotlinx.serialization.SerializationException: Serializer for class 'Any' is not found. Mark the class as @Serializable or provide the serializer explicitly. at kotlinx.serialization.internal.Platform_commonKt.serializerNotRegistered(Platform.common.kt:127) at kotlinx.serialization.ContextualSerializer.serialize(ContextualSerializer.kt:52) at kotlinx.serialization.json.internal.StreamingJsonEncoder.encodeSerializableValue(StreamingJsonEncoder.kt:223) at kotlinx.serialization.encoding.Encoder$DefaultImpls.encodeNullableSerializableValue(Encoding.kt:296) at kotlinx.serialization.json.JsonEncoder$DefaultImpls.encodeNullableSerializableValue(JsonEncoder.kt) at kotlinx.serialization.json.internal.StreamingJsonEncoder.encodeNullableSerializableValue(StreamingJsonEncoder.kt:15) at kotlinx.serialization.encoding.AbstractEncoder.encodeNullableSerializableElement(AbstractEncoder.kt:94) at DataBox.write$Self(main.kt) at DataBox$$serializer.serialize(main.kt) at DataBox$$serializer.serialize(main.kt:32) at kotlinx.serialization.json.internal.StreamingJsonEncoder.encodeSerializableValue(StreamingJsonEncoder.kt:223) at kotlinx.serialization.json.Json.encodeToString(Json.kt:73) at MainKt.test3(main.kt:138)

    Expected behavior Expect the behavior of 1.4.0 + 1.0.0-RC same as one of 1.3.70 + 0.20.0

    Environment

    • Kotlin version: 1.4.0
    • Library version: 1.0.0-RC
    • Kotlin platforms: JVM
    • Gradle version: 6.3
    • IDE version: IntellijIDEA 2020.2.1 Other relevant context : MacOS 10.12.6, JDK 1.8.0_261
    design docs needed 
    opened by rwsbillyang 24
  • Can't locate companion serializer for class class List

    Can't locate companion serializer for class class List

    The documentation mentiones that serializing lists is supported, but I can't seem to get it working.

    When running this code in Kotlin-JS:

    import kotlinx.serialization.Serializable
    import kotlinx.serialization.json.JSON
    
    fun main(args: Array<String>) {
        val list = listOf(Foo("a"), Foo("b"))
        println(JSON.stringify(list))
    }
    
    @Serializable
    data class Foo(val foo: String?)
    

    I get the exception SerializationException "Can't locate companion serializer for class class List". I'm using Kotlin version 1.1.50 and kotlinx.serialization version 0.2.

    question 
    opened by KarelPeeters 21
  • Android project: 1.0.0RC - Need gradle 6.1.1, does not work with 5.6.4

    Android project: 1.0.0RC - Need gradle 6.1.1, does not work with 5.6.4

    Since upgrade from 0.20.0 to 1.0.0-RC along with Kotlin to 1.4.0 the application fails to build with multiple errors in ::sample:checkDebugDuplicateClasses task with messages like:

    java.lang.RuntimeException: 
    Duplicate class kotlinx.serialization.AbstractSerialFormat found in modules 
    jetified-kotlinx-serialization-core-jvm-1.0.0-RC.jar (org.jetbrains.kotlinx:kotlinx-serialization-core-jvm:1.0.0-RC) and 
    jetified-kotlinx-serialization-core-jvm-1.0.0-RC.jar (org.jetbrains.kotlinx:kotlinx-serialization-core:1.0.0-RC)
    

    It seems the problem is actual with gradle 5.6.4 and a workaround by upgrading to 6.1.1 fixes the problem. However this bump of major gradle version may not be that easy in many cases. Is it intended or is it a bug? The need for gradle upgrade is not mentioned in migration guide explicitly.

    To Reproduce A sample application using the library with kotlinx.serialization dependency.

    1. include the library to see build failure. Commit
    2. Update gradle to 6.1.1 - build passes. Commit

    The library using serialization could be found in the same repository. Here is how the dependency is configured.

    Environment

    • Kotlin version: 1.4.0
    • Library version: 1.0.0-RC
    • Kotlin platforms: JVM (Android)
    • Gradle version: 5.6.4/6.1.1
    • AGP 3.6.3
    opened by motorro 20
  • Json decoding using non JsonOutput

    Json decoding using non JsonOutput

    For now, it is impossible to decode JsonElement from decoder inside of serializer if that decoder was not created by Json. Example:

    object : KSerializer<Any> {
        override val descriptor = StringDescriptor.withName("Example")
    
        override fun deserialize(decoder: Decoder) {
            val json = JsonElementSerializer.deserialize(decoder)
        }
    
        override serialize(encoder: Encoder, obj: Any) {
            TODO()
        }
    }
    

    Object will throw exception in deserialize method each time when this serializer will not be used with Json formatter.

    Is it possible to solve this problem?

    feature json 
    opened by InsanusMokrassar 20
  • Unable to get inline class serialized

    Unable to get inline class serialized

    I tried to serialize an inlined class. The class is implemented in the commons project of a MPP. The compiler arg "-XXLanguage:+InlineClasses" is defined in the JVM and JS project.

    Class:

    @Serializable
    inline class DeviceId(val value: String) {
        override fun toString(): String = value
    }
    

    And get the following exception:

    The root cause was thrown at: ImplementationBodyCodegen.java:863
    	at org.jetbrains.kotlin.codegen.CompilationErrorHandler.lambda$static$0(CompilationErrorHandler.java:24)
    	at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generate(PackageCodegenImpl.java:74)
    	at org.jetbrains.kotlin.codegen.DefaultCodegenFactory.generatePackage(CodegenFactory.kt:97)
    	at org.jetbrains.kotlin.codegen.DefaultCodegenFactory.generateModule(CodegenFactory.kt:68)
    	at org.jetbrains.kotlin.codegen.KotlinCodegenFacade.doGenerateFiles(KotlinCodegenFacade.java:47)
    	at org.jetbrains.kotlin.codegen.KotlinCodegenFacade.compileCorrectFiles(KotlinCodegenFacade.java:39)
    	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.generate(KotlinToJVMBytecodeCompiler.kt:446)
    	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:142)
    	at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:161)
    	at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:57)
    	at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:96)
    	at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:52)
    	at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:93)
    	at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:362)
    	at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:102)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compileIncrementally(IncrementalCompilerRunner.kt:225)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.access$compileIncrementally(IncrementalCompilerRunner.kt:39)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner$compile$2.invoke(IncrementalCompilerRunner.kt:91)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compile(IncrementalCompilerRunner.kt:103)
    	at org.jetbrains.kotlin.daemon.CompileServiceImpl.execIncrementalCompiler(CompileServiceImpl.kt:606)
    	at org.jetbrains.kotlin.daemon.CompileServiceImpl.access$execIncrementalCompiler(CompileServiceImpl.kt:102)
    	at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:455)
    	at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:102)
    	at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:1029)
    	at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:102)
    	at org.jetbrains.kotlin.daemon.common.DummyProfiler.withMeasure(PerfUtils.kt:137)
    	at org.jetbrains.kotlin.daemon.CompileServiceImpl.checkedCompile(CompileServiceImpl.kt:1071)
    	at org.jetbrains.kotlin.daemon.CompileServiceImpl.doCompile(CompileServiceImpl.kt:1028)
    	at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:454)
    	at sun.reflect.GeneratedMethodAccessor103.invoke(Unknown Source)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	at java.lang.reflect.Method.invoke(Method.java:498)
    	at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:357)
    	at sun.rmi.transport.Transport$1.run(Transport.java:200)
    	at sun.rmi.transport.Transport$1.run(Transport.java:197)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    	at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:573)
    	at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:834)
    	at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:688)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:687)
    	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    	at java.lang.Thread.run(Thread.java:748)
    Caused by: java.lang.ClassCastException: org.jetbrains.kotlin.codegen.ErasedInlineClassBodyCodegen cannot be cast to org.jetbrains.kotlin.codegen.ImplementationBodyCodegen
    	at org.jetbrains.kotlin.codegen.ImplementationBodyCodegen.initializeObjects(ImplementationBodyCodegen.java:863)
    	at org.jetbrains.kotlin.codegen.ImplementationBodyCodegen.generateSyntheticPartsAfterBody(ImplementationBodyCodegen.java:410)
    	at org.jetbrains.kotlin.codegen.MemberCodegen.generate(MemberCodegen.java:130)
    	at org.jetbrains.kotlin.codegen.MemberCodegen.genClassOrObject(MemberCodegen.java:300)
    	at org.jetbrains.kotlin.codegen.MemberCodegen.genSyntheticClassOrObject(MemberCodegen.java:314)
    	at org.jetbrains.kotlin.codegen.ClassBodyCodegen.generateBody(ClassBodyCodegen.java:100)
    	at org.jetbrains.kotlin.codegen.MemberCodegen.generate(MemberCodegen.java:127)
    	at org.jetbrains.kotlin.codegen.ImplementationBodyCodegen.generateErasedInlineClassIfNeeded(ImplementationBodyCodegen.java:263)
    	at org.jetbrains.kotlin.codegen.ClassBodyCodegen.generateBody(ClassBodyCodegen.java:85)
    	at org.jetbrains.kotlin.codegen.MemberCodegen.generate(MemberCodegen.java:127)
    	at org.jetbrains.kotlin.codegen.MemberCodegen.genClassOrObject(MemberCodegen.java:300)
    	at org.jetbrains.kotlin.codegen.MemberCodegen.genClassOrObject(MemberCodegen.java:284)
    	at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generateClassOrObject(PackageCodegenImpl.java:161)
    	at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generateClassesAndObjectsInFile(PackageCodegenImpl.java:86)
    	at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generateFile(PackageCodegenImpl.java:119)
    	at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generate(PackageCodegenImpl.java:66)
    	... 43 more
    
    bug feature 
    opened by wem 20
  • Add support for numeric json class discriminators

    Add support for numeric json class discriminators

    What is your use-case and why do you need this feature?

    Many APIs such as Discord use type codes, which align very closely to this library's JsonClassDiscriminator feature. However, these type codes are frequently numeric instead of strings, which makes them incompatible with this library without complex workarounds.

    Describe the solution you'd like

    I would prefer a solution which adds an option to specify the serialized type of a discriminator, such as an addition annotation parameter as an enum of supported types, defaulting to string

    feature design 
    opened by JesseCorbett 2
  • Un-actionable Gradle warning: There are multiple versions of

    Un-actionable Gradle warning: There are multiple versions of "kotlin" used in nodejs build: 1.7.20, 1.7.21.

    Describe the bug

    A gradle warning occurs, likely due to kotlinx.serialization:

    There are multiple versions of "kotlin" used in nodejs build: 1.7.20, 1.7.21. Only latest version will be used.

    I use kotlinx.serialization 1.4.1 as a dependency of our custom Gradle plugin. We then execute our main project, which uses this plugin, in an environment where all kotlin versions are 1.7.21.

    I have not confirmed 100% that kotlinx.serialization is causing the warning. However, I'm pretty sure it is. kotlinx.serialization 1.4.1 uses kotlin 1.7.20, so it seems likely.

    To Reproduce

    It occurs in every single one of my gradle builds. Creating a reproducer might take a bit of time, but essentially:

    1. Build a custom gradle plugin that depends on kotlinx.serialization 1.4.1
    2. Use that custom gradle plugin in a project that is using kotlin 1.7.21

    Expected behavior

    For there to be no warnings

    Proposed solution

    Create a minor release where the kotlin version is bumped to 1.7.21

    wontfix 
    opened by mgroth0 1
  • CompilationException on expected class with companion object

    CompilationException on expected class with companion object

    Describe the bug

    I get a compilation exception for an expected class with a companion object.

    Details: kotlinx.serialization compiler plugin internal error: unable to transform declaration, see cause
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializerClassLowering.lower(SerializationLoweringExtension.kt:184)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt$runOnFileInOrder$1.visitClass(SerializationLoweringExtension.kt:46)
    	at org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid$DefaultImpls.visitClass(IrElementVisitorVoid.kt:111)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt$runOnFileInOrder$1.visitClass(SerializationLoweringExtension.kt:40)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt$runOnFileInOrder$1.visitClass(SerializationLoweringExtension.kt:40)
    	at org.jetbrains.kotlin.ir.declarations.IrClass.accept(IrClass.kt:64)
    	at org.jetbrains.kotlin.ir.declarations.IrClass.acceptChildren(IrClass.kt:68)
    	at org.jetbrains.kotlin.ir.visitors.IrVisitorsKt.acceptChildrenVoid(IrVisitors.kt:15)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt$runOnFileInOrder$1.visitClass(SerializationLoweringExtension.kt:47)
    	at org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid$DefaultImpls.visitClass(IrElementVisitorVoid.kt:111)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt$runOnFileInOrder$1.visitClass(SerializationLoweringExtension.kt:40)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt$runOnFileInOrder$1.visitClass(SerializationLoweringExtension.kt:40)
    	at org.jetbrains.kotlin.ir.declarations.IrClass.accept(IrClass.kt:64)
    	at org.jetbrains.kotlin.ir.declarations.IrFile.acceptChildren(IrFile.kt:36)
    	at org.jetbrains.kotlin.ir.visitors.IrVisitorsKt.acceptChildrenVoid(IrVisitors.kt:15)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt$runOnFileInOrder$1.visitElement(SerializationLoweringExtension.kt:42)
    	at org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid$DefaultImpls.visitPackageFragment(IrElementVisitorVoid.kt:190)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt$runOnFileInOrder$1.visitPackageFragment(SerializationLoweringExtension.kt:40)
    	at org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid$DefaultImpls.visitFile(IrElementVisitorVoid.kt:200)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt$runOnFileInOrder$1.visitFile(SerializationLoweringExtension.kt:40)
    	at org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid$DefaultImpls.visitFile(IrElementVisitorVoid.kt:198)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt$runOnFileInOrder$1.visitFile(SerializationLoweringExtension.kt:40)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt$runOnFileInOrder$1.visitFile(SerializationLoweringExtension.kt:40)
    	at org.jetbrains.kotlin.ir.declarations.IrFile.accept(IrFile.kt:30)
    	at org.jetbrains.kotlin.ir.visitors.IrVisitorsKt.acceptVoid(IrVisitors.kt:11)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtensionKt.runOnFileInOrder(SerializationLoweringExtension.kt:40)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtension.generate(SerializationLoweringExtension.kt:149)
    	at org.jetbrains.kotlin.backend.jvm.JvmIrCodegenFactory.convertToIr$lambda$1(JvmIrCodegenFactory.kt:186)
    	at org.jetbrains.kotlin.psi2ir.Psi2IrTranslator.generateModuleFragment(Psi2IrTranslator.kt:104)
    	at org.jetbrains.kotlin.backend.jvm.JvmIrCodegenFactory.convertToIr(JvmIrCodegenFactory.kt:218)
    	at org.jetbrains.kotlin.backend.jvm.JvmIrCodegenFactory.convertToIr(JvmIrCodegenFactory.kt:55)
    	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.convertToIr(KotlinToJVMBytecodeCompiler.kt:225)
    	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:102)
    	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli$default(KotlinToJVMBytecodeCompiler.kt:47)
    	at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:167)
    	at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:53)
    	at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:101)
    	at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:47)
    	at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:101)
    	at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:485)
    	at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:131)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.doCompile(IncrementalCompilerRunner.kt:424)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compileImpl(IncrementalCompilerRunner.kt:360)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compileNonIncrementally(IncrementalCompilerRunner.kt:242)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compile(IncrementalCompilerRunner.kt:98)
    	at org.jetbrains.kotlin.daemon.CompileServiceImplBase.execIncrementalCompiler(CompileServiceImpl.kt:625)
    	at org.jetbrains.kotlin.daemon.CompileServiceImplBase.access$execIncrementalCompiler(CompileServiceImpl.kt:101)
    	at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:1746)
    	at jdk.internal.reflect.GeneratedMethodAccessor103.invoke(Unknown Source)
    	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    	at java.rmi/sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:359)
    	at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:200)
    	at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:197)
    	at java.base/java.security.AccessController.doPrivileged(Native Method)
    	at java.rmi/sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    	at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:562)
    	at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:796)
    	at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:677)
    	at java.base/java.security.AccessController.doPrivileged(Native Method)
    	at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:676)
    	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    	at java.base/java.lang.Thread.run(Thread.java:829)
    Caused by: java.lang.IllegalStateException: Expected to have a primary constructor
    	at org.jetbrains.kotlinx.serialization.compiler.backend.ir.Fir2IrGeneratorUtilsKt.getPrimary(Fir2IrGeneratorUtils.kt:41)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.ir.Fir2IrGeneratorUtilsKt.addDefaultConstructorIfAbsent(Fir2IrGeneratorUtils.kt:44)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.ir.SerializableCompanionIrGenerator$Companion.generate(SerializableCompanionIrGenerator.kt:53)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializerClassLowering.lower(SerializationLoweringExtension.kt:104)
    	... 63 more
    

    To Reproduce

    Common sources:

    @Serializable
    expect class Expected {
        companion object { fun factoryMethod(): Expected }
    }
    

    JVM and JS sources (they are identical):

    @Serializable
    actual class Expected
    {
        actual companion object { actual fun factoryMethod(): Expected = Expected() }
    }
    

    Expected behavior

    Compilation which succeeds. :)

    Environment

    • Kotlin version: 1.8.0-RC
    • Library version: 1.4.1
    • Kotlin platforms: JVM, JS
    • Gradle version: 7.4
    bug compiler-plugin 
    opened by Whathecode 2
  • Support encode/decode java.time.temporal.TemporalAmount in HOCON

    Support encode/decode java.time.temporal.TemporalAmount in HOCON

    The typesafe.config library supports decoding java.time.temporal.TemporalAmount objects using the com.typesafe.config.Config.getTemporal method. Implemented support for this functionality in the Hocon module.

    Depends on: #2094, #2126

    opened by alexmihailov 0
Releases(v1.4.1)
  • v1.4.1(Oct 17, 2022)

    This patch release contains several bug fixes and improvements. Kotlin 1.7.20 is used by default.

    Improvements

    • Add @MustBeDocumented to certain annotations (#2059)
    • Deprecate .isNullable in SerialDescriptor builder (#2040)
    • Unsigned primitives and unsigned arrays serializers can be retrieved as built-ins (#1992)
    • Serializers are now cached inside reflective lookup, leading to faster serializer retrieval (#2015)
    • Compiler plugin can create enum serializers using static factories for better speed (#1851) (Kotlin 1.7.20 required)
    • Provide a foundation for compiler plugin intrinsics available in Kotlin 1.8.0 (#2031)

    Bugfixes

    • Support polymorphism in Properties format (#2052) (thanks to Rodrigo Vedovato)
    • Added support of UTF-16 surrogate pairs to okio streams (#2033)
    • Fix dependency on core module from HOCON module (#2020) (thanks to Osip Fatkullin)
    Source code(tar.gz)
    Source code(zip)
  • v1.4.0(Aug 18, 2022)

    This release contains all features and bugfixes from 1.4.0-RC plus some bugfixes on its own (see below). Kotlin 1.7.10 is used as a default.

    Bugfixes

    • Fixed decoding of huge JSON data for okio streams (#2006)
    Source code(tar.gz)
    Source code(zip)
  • v1.4.0-RC(Jul 20, 2022)

    This is a candidate for the next big release with many new exciting features to try. It uses Kotlin 1.7.10 by default.

    Integration with Okio's BufferedSource and BufferedSink

    Okio library by Square is a popular solution for fast and efficient IO operations on JVM, K/N and K/JS. In this version, we have added functions that parse/write JSON directly to Okio's input/output classes, saving you the overhead of copying data to String beforehand. These functions are called Json.decodeFromBufferedSource and Json.encodeToBufferedSink, respectively. There's also decodeBufferedSourceToSequence that behaves similarly to decodeToSequence from Java streams integration, so you can lazily decode multiple objects the same way as before.

    Note that these functions are located in a separate new artifact, so users who don't need them wouldn't find themselves dependent on Okio. To include this artifact in your project, use the same group id org.jetbrains.kotlinx and artifact id kotlinx-serialization-json-okio. To find out more about this integration, check new functions' documentation and corresponding pull requests: #1901 and #1982.

    Inline classes and unsigned numbers do not require experimental annotations anymore

    Inline classes and unsigned number types have been promoted to a Stable feature in Kotlin 1.5, and now we are promoting support for them in kotlinx.serialization to Stable status, too. To be precise, we've removed all @ExperimentalSerializationApi annotations from functions related to inline classes encoding and decoding, namely SerialDescriptor.isInline, Encoder.encodeInline, and some others. We've also updated related documentation article.

    Additionally, all @ExperimentalUnsignedTypes annotations were removed completely, so you can freely use types such as UInt and their respective serializers as a stable feature without opt-in requirement.

    Part of SerializationException's hierarchy is public now

    When kotlinx.serialization 1.0 was released, all subclasses of SerializationException were made internal, since they didn't provide helpful information besides the standard message. Since then, we've received a lot of feature requests with compelling use-cases for exposing some of these internal types to the public. In this release, we are starting to fulfilling these requests by making MissingFieldException public. One can use it in the catch clause to better understand the reasons of failure — for example, to return 400 instead of 500 from an HTTP server — and then use its fields property to communicate the message better. See the details in the corresponding PR.

    In future releases, we'll continue work in this direction, and we aim to provide more useful public exception types & properties. In the meantime, we've revamped KDoc for some methods regarding the exceptions — all of them now properly declare which exception types are allowed to be thrown. For example, KSerializer.deserialize is documented to throw IllegalStateException to indicate problems unrelated to serialization, such as data validation in classes' constructors.

    @MetaSerializable annotation

    This release introduces a new @MetaSerializable annotation that adds @Serializable behavior to user-defined annotations — i.e., those annotations would also instruct the compiler plugin to generate a serializer for class. In addition, all annotations marked with @MetaSerializable are saved in the generated @SerialDescriptor as if they are annotated with @SerialInfo.

    This annotation will be particularly useful for various format authors who require adding some metadata to the serializable class — this can now be done using a single annotation instead of two, and without the risk of forgetting @Serializable. Check out details & examples in the KDoc and corresponding PR.

    Note: Kotlin 1.7.0 or higher is required for this feature to work.

    Moving documentation from GitHub pages to kotlinlang.org

    As a part of a coordinated effort to unify kotlinx libraries users' experience, Dokka-generated documentation pages (KDoc) were moved from https://kotlin.github.io/kotlinx.serialization/ to https://kotlinlang.org/api/kotlinx.serialization/. No action from you is required — there are proper redirects at the former address, so there is no need to worry about links in your blogpost getting obsolete or broken.

    Note that this move does not affect guides written in Markdown in the docs folder. We aim to move them later, enriching text with runnable examples as in the Kotlin language guides.

    Other improvements

    • Allow Kotlin's null literal in JSON DSL (#1907) (thanks to Lukellmann)
    • Stabilize EmptySerializersModule (#1921)
    • Boost performance of polymorphic deserialization in optimistic scenario (#1919)
    • Added serializer for the kotlin.time.Duration class (plugin support comes in Kotlin 1.7.20) (#1960)
    • Support tagged not null marks in TaggedEncoder/Decoder (#1954) (thanks to EdwarDDay)

    Bugfixes

    • Support quoting unsigned integers when used as map keys (#1969)
    • Fix protocol buffer enum schema generation (#1967) (thanks to mogud)
    • Support diamond inheritance of sealed interfaces in SealedClassSerializer (#1958)
    • Support retrieving serializer for sealed interface (#1968)
    • Fix misleading token description in JSON errors (#1941) (thanks to TheMrMilchmann)
    Source code(tar.gz)
    Source code(zip)
  • v1.3.3(May 12, 2022)

    This release contains support for Protocol Buffers packed fields, as well as several bugfixes. It uses Kotlin 1.6.21 by default.

    Protobuf packed fields

    It is now possible to encode and decode Kotlin classes to/from Protobuf messages with packed repeated fields. To mark the field as packed, use @ProtoPacked annotation on it. Note it affects only List and primitive collection such as IntArray types. With this feature, it is now possible to decode Proto3 messages, where all repeated fields are packed by default. Protobuf schema generator also supports new @ProtoPacked annotation.

    Many thanks to Paul de Vrieze for his valuable contribution!

    Other improvements & small features

    • Incorporate JsonPath into exception messages (#1841)
    • Mark block in corresponding encodeStructure/decodeStructure extensions as crossinline to reduce amount of bytecode (#1917)
    • Support serialization of compile-time Collection<E> properties that are not lists at the runtime (#1821)
    • Best-effort kotlin reflect avoidance in serializer(Type) (#1819)

    Bugfixes

    • Iterate over element indices in ObjectSerializer in order to let the format skip unknown keys (#1916)
    • Correctly support registering both default polymorphic serializer & deserializer (#1849)
    • Make error message for captured generic type parameters much more straightforward (#1863)
    Source code(tar.gz)
    Source code(zip)
  • v1.3.2(Dec 23, 2021)

    This release contains several features and bugfixes for core API as well as for HOCON format. It uses Kotlin 1.6.10 by default.

    Serializing objects to HOCON

    It's now possible to encode Kotlin objects to Config values with new Hocon.encodeToConfig function. This feature may help edit existing configs inside Kotlin program or generate new ones.

    Big thanks to Osip Fatkullin for implementing this.

    Polymorphic default serializers

    As of now, polymorphicDefault clause inside SerializersModule { } builder specifies a fallback serializer to be used only during deserialization process. A new function has been introduced to allow setting fallback serializer for serialization: polymorphicDefaultSerializer. This function should ease serializing vast hierarchies of third-party or Java classes.

    Note that there are two new experimental functions, polymorphicDefaultSerializer and polymorphicDefaultDeserializer. To avoid naming confusion, we are going to deprecate polymorphicDefault in favor of polymorphicDefaultDeserializer in the next minor release (1.4.0).

    Credit for the PR goes to our contributor Joseph Burton.

    Other improvements

    • HOCON: parse strings into integers and booleans if possible (#1795) (thanks to tobiaslieber)
    • Add an encodeCollection extensions (#1749) (thanks to Nicklas Ansman Giertz)

    Bugfixes

    • Properly handle top-level value classes in encodeToJsonElement (#1777)
    • Fix incorrect handling of object end when JsonTreeReader (JsonElement) is used with decodeToSequence (#1782)
    Source code(tar.gz)
    Source code(zip)
  • v1.3.1(Nov 11, 2021)

    This release mainly contains bugfixes for 1.3.0 and provides new experimental Json.decodeToSequence function.

    Improvements

    • Provide decodeToSequence to read multiple objects from stream lazily (#1691)

    Bugfixes

    • Correctly handle buffer boundaries while decoding escape sequences from json stream (#1706)
    • Properly skip unknown keys for objects and structures with zero properties (#1720)
    • Fix merging for maplikeSerializer when the map is not empty (by using the actual size * 2). (#1712) (thanks to pdvrieze)
    • Fix lookup of primitive array serializers by Java type token (#1708)
    Source code(tar.gz)
    Source code(zip)
  • v1.3.0(Sep 24, 2021)

    This release contains all of the cool new features from 1.3.0-RC as well as minor improvements. It uses Kotlin 1.5.31 by default.

    Bugfixes and improvements

    • Promote JsonConfiguration and its usages to stable (#1690)
    • Remove opt-in annotations from SerialFormat, StringFormat, BinaryFormat (#1688)
    • Correctly throw SerializationException instead of IOOBE for some cases with EOF in streams (#1677)
    • CBOR: ignore tags when reading (#1614) (thanks to David Robertson)
    Source code(tar.gz)
    Source code(zip)
  • v1.3.0-RC(Sep 6, 2021)

    This is a release candidate for the next version. It contains a lot of interesting features and improvements, so we ask you to evaluate it and share your feedback. Kotlin 1.5.30 is used by default.

    Java IO stream-based JSON serialization

    Finally, in kotlinx.serialization 1.3.0 we’re presenting the first experimental version of the serialization API for IO streams: Json.encodeToStream and Json.decodeFromStream extension functions. With this API, you can decode objects directly from files, network connections, and other data sources without reading the data to strings beforehand. The opposite operation is also available: you can send encoded objects directly to files and other streams in a single API call. IO stream serialization is available only on the JVM platform and for the JSON format for now.

    Check out more in the PR.

    Property-level control over defaults values encoding

    Previous versions of the library allowed to specify whether to encode or drop default properties values with format configuration flags such as Json { encodeDefaults = false }. In 1.3.0 we’re extending this feature by adding a new way to fine-tune the serialization of default values: you can now control it on the property level using the new @EncodeDefault annotation.

    @EncodeDefault annotation has a higher priority over the encodeDefaults property and takes one of two possible values:

    • ALWAYS (default value) encodes a property value even if it equals to default.
    • NEVER doesn’t encode the default value regardless of the format configuration.

    Encoding of the annotated properties is not affected by encodeDefaults format flag and works as described for all serialization formats, not only JSON.

    To learn more, check corresponding PR.

    Excluding null values from JSON serialization

    In 1.3.0, we’re introducing one more way to reduce the size of the generated JSON strings: omitting null values. A new JSON configuration property explicitNulls defines whether null property values should be included in the serialized JSON string. The difference from encodeDefaults is that explicitNulls = false flag drops null values even if the property does not have a default value. Upon deserializing such a missing property, a null or default value (if it exists) will be used.

    To maintain backwards compatibility, this flag is set to true by default. You can learn more in the documentation or the PR.

    Per-hierarchy polymorphic class discriminators

    In previous versions, you could change the discriminator name using the classDiscriminator property of the Json instance. In 1.3.0, we’re adding a way to set a custom discriminator name for each class hierarchy to enable more flexible serialization. You can do it by annotating a class with @JsonClassDiscriminator with the discriminator name as its argument. A custom discriminator is applied to the annotated class and its subclasses. Only one custom discriminator can be used in each class hierarchy, thanks to the new @InheritableSerialInfo annotation.

    Check out corresponding PR for details.

    Support for Java module system

    Now all kotlinx.serialization runtime libraries are shipped as a multi-release JAR with module-info.class file for Java versions 9 and higher. This enables possibilities to use kotlinx.serialization with modern tools such as jlink and various technologies such as TorandoFX.

    Many thanks to our contributor Gerard de Leeuw and his PR for making this possible.

    Native targets for Apple Silicon

    This release includes klibs for new targets, introduced in Kotlin/Native 1.5.30 — macosArm64, iosSimulatorArm64, watchosSimulatorArm64, and tvosSimulatorArm64.

    Bugfixes and improvements

    • Properly handle quoted 'null' literals in lenient mode (#1637)
    • Switch on deep recursive function when nested level of JSON is too deep (#1596)
    • Support for local serializable classes in IR compiler
    • Support default values for @SerialInfo annotations in IR compiler
    • Improve error message for JsonTreeReader (#1597)
    • Add guide for delegating serializers and wrapping serial descriptor (#1591)
    • Set target JVM version to 8 for Hocon module in Gradle metadata (#1661)
    Source code(tar.gz)
    Source code(zip)
  • v1.2.2(Jul 8, 2021)

    This release contains various bugfixes, some useful features and important performance improvements. It also uses Kotlin 1.5.20 as default.

    Features

    • Support for @JsonNames and coerceInputValues in Json.decodeFromDynamic (#1479)
    • Add factory function to wrap a serial descriptor with a custom name for custom delegating serializers (#1547) (thanks to Fadenfire)
    • Allow contextually serialized types to be used as map keys in Json (#1552) (thanks to pdvrieze)

    Bugfixes and performance improvements

    • Update size in JsonStringBuilder slow-path to avoid excessive array-copies for large strings with escape symbols (#1491)
    • Optimize integer encoding length in CBOR (#1570) (thanks to davertay)
    • Throw JsonDecodingException instead of ClassCastException during unexpected null in TreeJsonDecoder (#1550)
    • Prohibit 'null' strings in lenient mode in order to get rid of 'null' and "null" ambiguity (#1549)
    • Avoid usage of reflective-like serialDescriptor<KType> in production sources (#1540)
    • Added correct error message when deserializing missing enum member for Properties format (#1539)
    • Make DescriptorSchemaCache in Json thread-local on Native (#1484)
    Source code(tar.gz)
    Source code(zip)
  • v1.2.1(May 13, 2021)

    This release mainly contains bugfixes for various issues, including important broken thread-safety and improper encoding.

    Features

    • Added support for nullable values, nested and empty collections in protobuf (#1430)

    Bugfixes

    • Support @JsonNames for enum values (#1473)
    • Handle EOF in skipElement correctly (#1475)
    • Allow using value classes with primitive carriers as map keys (#1470)
    • Read JsonNull only for non-string literals in JsonTreeReader (#1466)
    • Properly reuse JsonStringBuilders in CharArrayPool (#1455)
    • Properly ensure capacity of the string builder on the append slow-path (#1441)
    Source code(tar.gz)
    Source code(zip)
  • v1.2.0(Apr 28, 2021)

    This release has some known critical bugs, so we advise to use 1.2.1 instead.

    This release contains a lot of new features and important improvements listed below; Kotlin 1.5.0 is used as a default compiler and language version.

    JSON performance improvements

    JSON encoder and decoder were revisited and significantly rewritten, which lead us to up to 2-3x times speedup in certain cases. Additional details can be found in the corresponding pull requests: [1], [2].

    Ability to specify alternative names during JSON decoding

    The one of the most voted issues is fixed now — it is possible to specify multiple names for one property using new @JsonNames annotation. Unlike @SerialName, it only affects JSON decoding, so it is useful when dealing with different versions of the API. We've prepared a documentation for you about it.

    JsonConfiguration in public API

    JsonConfiguration is exposed as a property of Json instance. You can use it to adjust behavior in your custom serializers. Check out more in the corresponding issue and the PR.

    Generator for .proto files based on serializable Kotlin classes

    Our implementation of Protocol Buffers format uses @Serializable Kotlin classes as a source of schema. This is very convenient for Kotlin-to-Kotlin communication, but makes interoperability between languages complicated. To resolve this issue, we now have a schema generator that can produce .proto files out of Kotlin classes. Using it, you can keep Kotlin classes as a source of truth and use traditional protoc compilers for other languages at the same time. To learn more, check out the documentation for the new ProtoBufSchemaGenerator class or visit the corresponding PR.

    Note: this generator is on its experimental stage and any feedback is very welcomed.

    Contextual serialization of generic classes

    Before 1.2.0, it was impossible to register context serializer for generic class, because contextual function accepted a single serializer. Now it is possible to register a provider — lambda that allows to construct a serializer for generic class out of its type arguments serializers. See the details in the documentation.

    Other features

    • Support for watchosX64 target (#1366).
    • Introduce kotlinx-serialization-bom (#1356).
    • Support serializer on JS IR when T is an interface (#1431).

    Bugfixes

    • Fix serializer lookup by KType for third party classes (#1397) (thanks to mvdbos).
    • Fix inability to encode/decode inline class with string to JsonElement (#1408).
    • Throw SerializationException instead of AIOB in ProtoBuf (#1373).
    • Fix numeric overflow in JsonLexer (#1367) (thanks to EdwarDDay).
    Source code(tar.gz)
    Source code(zip)
  • v1.1.0(Feb 19, 2021)

    This release contains all features and bugfixes from 1.1.0-RC plus an additional fix for incorrect exception type (#1325 — Throw SerializationException instead of IllegalStateException in EnumSerializer) and uses release version of Kotlin 1.4.30.

    In the light of JCenter shutdown, starting from 1.1.0-RC and now on, all new releases of kotlinx.serialization are published directly to Maven Central and therefore are not available in https://kotlin.bintray.com/kotlinx/ repository. We suggest you to remove jcenter() and other kotlin bintray repositories from your buildscripts and to use mavenCentral() repository instead.

    Source code(tar.gz)
    Source code(zip)
  • v1.1.0-RC(Feb 4, 2021)

    This is a release candidate of 1.1.0 version. Note that final 1.1.0 version may include more features and bugfixes, which would be listed in the corresponding changelog.

    Kotlin version requirement updated

    Due to changes in calling conventions between compiler plugin and serialization core runtime, this release requires Kotlin version at least 1.4.30-M1 (we recommend using 1.4.30 release version). However, these changes should not affect your code, because only deprecated functions were removed from public API. See corresponding PR for the details.

    Experimental support for inline classes (IR only)

    Using 1.1.0-RC, you can mark inline classes as @Serializable and use them in other serializable classes. Unsigned integer types (UByte, UShort, UInt and ULong) are serializable as well and have special support in JSON. This feature requires Kotlin compiler 1.4.30-RC and enabling new IR compilers for JS and JVM.

    You can learn more in the documentation and corresponding pull request.

    Other features

    • Add serializerOrNull function for KType and Type arguments (#1164)
    • Allow shared prefix names in Properties (#1183) (thanks to TorRanfelt)
    • Add support for encoding/decoding Properties values as Strings (#1158) (thanks to daniel-jasinski)

    Bugfixes and performance improvements

    • Support contextual serialization for derived classes (#1277) (thanks to Martin Raison)
    • Ensure serialization is usable from K/N background thread (#1282)
    • Fail on primitive type overflow during JsonElement deserialization (#1300)
    • Throw SerializationException instead of ISE when encountering an invalid boolean in JSON (#1299)
    • Optimize the loop for writing large varints in ProtoBuf (#1294)
    • Fix serializing property with custom accessors and backing field (#1197)
    • Optimize check for missing fields in deserialization and improve MissingFieldException message (#1153)
    • Improved support of nullable serializer in @UseSerializers annotation (#1195)
    • Correctly escape keys in JsonObject.toString() (#1246) (thanks to Karlatemp)
    • Treat Collection as ArrayList in serializer by type lookups (#1257)
    • Do not try to end structure in encode/decode structure extensions if an exception has been thrown, so the original exception will be propagated (#1201)
    • Properly cache serial names in order to improve performance of JSON parser with strict mode (#1209)
    • Fix dynamic serialization for nullable values (#1199) (thanks to ankushg)
    Source code(tar.gz)
    Source code(zip)
  • v1.0.1(Oct 28, 2020)

    This patch release contains several feature improvements as well as bugfixes and performance improvements.

    Features

    • Add object-based serialization and deserialization of polymorphic types for dynamic conversions on JS platform (#1122)
    • Add support for object polymorphism in HOCON decoder (#1136)
    • Add support of decoding map in the root of HOCON config (#1106)

    Bugfixes

    • Properly cache generated serializers in PluginGeneratedSerialDescriptor (#1159)
    • Add Pair and Triple to serializer resolving from Java type token (#1160)
    • Fix deserialization of half-precision, float and double types in CBOR (#1112)
    • Fix ByteString annotation detection when ByteArray is nullable (#1139) (thanks to Travis Wyatt)
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(Oct 8, 2020)

    The first public stable release, yay! The definitions of stability and backwards compatibility guarantees are located in the corresponding document. We now also have a GitHub Pages site with full API reference.

    Compared to RC2, no new features apart from #947 were added and all previously deprecated declarations and migrations were deleted. If you are using RC/RC2 along with deprecated declarations, please, migrate before updating to 1.0.0. In case you are using pre-1.0 versions (e.g. 0.20.0), please refer to our migration guide.

    Bugfixes and improvements

    • Support nullable types at top-level for JsonElement decoding (#1117)
    • Add CBOR ignoreUnknownKeys option (#947) (thanks to Travis Wyatt)
    • Fix incorrect documentation of encodeDefaults (#1108) (thanks to Anders Carling)
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0-RC2(Sep 21, 2020)

    Second release candidate for 1.0.0 version. This RC contains tweaks and changes based on users feedback after 1.0.0-RC.

    Major changes

    JSON format is now located in different artifact (#994)

    In 1.0.0-RC, the kotlinx-serialization-core artifact contained core serialization entities as well as Json serial format. We've decided to change that and to make core format-agnostic. It would make the life easier for those who use other serial formats and also make possible to write your own implementation of JSON or another format without unnecessary dependency on the default one.

    In 1.0.0-RC2, Json class and related entities are located in kotlinx-serialization-json artifact. To migrate, simply replace kotlinx-serialization-core dependency with -json. Core library then will be included automatically as the transitive dependency.

    For most use-cases, you should use new kotlinx-serialization-json artifact. Use kotlinx-serialization-core if you are writing a library that depends on kotlinx.serialization in a format-agnostic way of provides its own serial format.

    encodeDefaults flag is now set to false in the default configuration for JSON, CBOR and Protocol Buffers.

    The change is motivated by the fact that in most real-life scenarios, this flag is set to false anyway, because such configuration reduces visual clutter and saves amount of data being serialized. Other libraries, like GSON and Moshi, also have this behavior by default.

    This may change how your serialized data looks like, if you have not set value for encodeDefaults flag explicitly. We anticipate that most users already had done this, so no migration is required. In case you need to return to the old behavior, simply add encodeDefaults = true to your configuration while creating Json/Cbor/ProtoBuf object.

    Move Json.encodeToDynamic/Json.decodeFromDynamic functions to json package

    Since these functions are no longer exposed via DynamicObjectParser/Serializer and they are now Json class extensions, they should be moved to kotlinx.serialization.json package. To migrate, simply add import kotlinx.serialization.json.* to your files.

    Bugfixes and improvements

    • Do not provide default implementation for serializersModule in AbstractEncoder/Decoder (#1089)
    • Support JsonElement hierarchy in dynamic encoding/decoding (#1080)
    • Support top-level primitives and primitive map keys in dynamic encoding/decoding
    • Change core annotations retention (#1083)
    • Fix 'Duplicate class ... found in modules' on Gradle != 6.1.1 (#996)
    • Various documentation clarifications
    • Support deserialization of top-level nullable types (#1038)
    • Make most serialization exceptions eligible for coroutines exception recovery (#1054)
    • Get rid of methods that do not present in Android API<24 (#1013, #1040)
    • Throw JsonDecodingException on empty string literal at the end of the input (#1011)
    • Remove new lines in deprecation warnings that caused errors in ObjC interop (#990)
    Source code(tar.gz)
    Source code(zip)
  • 1.0.0-RC(Aug 17, 2020)

    Release candidate for 1.0.0 version. The goal of RC release is to collect feedback from users and provide 1.0.0 release with bug fixes and improvements based on that feedback.

    While working on 1.0.0 version, we carefully examined every public API declaration of the library and split it to stable API, that we promise to be source and binary-compatible, and experimental API, that may be changed in the future. Experimental API is annotated with @ExperimentalSerializationApi annotation, which requires opt-in. For a more detailed description of the guarantees, please refer to the compatibility guide.

    The id of the core artifact with @Serializable annotation and Json format was changed from kotlinx-serialization-runtime to kotlinx-serialization-core to be more clear and aligned with other kotlinx libraries.

    A significant part of the public API was renamed or extracted to a separate package. To migrate from the previous versions of the library, please refer to the migration guide.

    API changes

    Json

    • Core API changes

      • stringify and parse are renamed to encodeToString and decodeFromString
      • parseJson and fromJson are renamed to parseToJsonElement and decodeFromJsonElement
      • Reified versions of methods are extracted to extensions
    • Json constructor is replaced with Json {} builder function, JsonConfiguration is deprecated in favor of Json {} builder

      • All default Json implementations are removed
      • Json companion object extends Json
    • Json configuration

      • prettyPrintIndent allows only whitespaces
      • serializeSpecialFloatingPointValues is renamed to allowSpecialFloatingPointValues. It now affects both serialization and deserialization behaviour
      • unquoted JSON flag is deprecated for removal
      • New coerceInputValues option for null-defaults and unknown enums (#90, #246)
    • Simplification of JsonElement API

      • Redundant members of JsonElement API are deprecated or extracted to extensions
      • Potential error-prone API is removed
      • JsonLiteral is deprecated in favor of JsonPrimitive constructors with nullable parameter
    • JsonElement builders rework to be aligned with stdlib collection builders (#418, #627)

      • Deprecated infix to and unaryPlus in JSON DSL in favor of put/add functions
      • jsonObject {} and json {} builders are renamed to buildJsonObject {} and buildJsonArray {}
      • Make all builders inline (#703)
    • JavaScript support

      • DynamicObjectParser is deprecated in the favor of Json.decodeFromDynamic extension functions
      • Json.encodeToDynamic extension is added as a counterpart to Json.decodeFromDynamic (former DynamicObjectParser) (#116)
    • Other API changes:

      • JsonInput and JsonOutput are renamed to JsonDecoder and JsonEncoder
      • Methods in JsonTransformingSerializer are renamed to transformSerialize and transformDeserialize
      • JsonParametricSerializer is renamed to JsonContentPolymorphicSerializer
      • JsonEncodingException and JsonDecodingException are made internal
    • Bug fixes

      • IllegalStateException when null occurs in JSON input in the place of an expected non-null object (#816)
      • java.util.NoSuchElementException when deserializing twice from the same JsonElement (#807)

    Core API for format authoring

    • The new naming scheme for SerialFormats

      • Core functions in StringFormat and BinaryFormat are renamed and now follow the same naming scheme
      • stringify/parse are renamed to encodeToString/decodeFromString
      • encodeToByteArray/encodeToHexString/decodeFromByteArray/decodeFromHexString in BinaryFormat are introduced instead of dump/dumps/load/loads
    • New format instances building convention

      • Constructors replaced with builder-function with the same name to have the ability to add new configuration parameters, while preserving both source and binary compatibility
      • Format's companion objects now extend format class and can be used interchangeably
    • SerialDescriptor-related API

      • SerialDescriptor and SerialKind are moved to a separate kotlinx.serialization.descriptors package
      • ENUM and CONTEXTUAL kinds now extend SerialKind directly
      • PrimitiveDescriptor is renamed to PrimitiveSerialDescriptor
      • Provide specific buildClassSerialDescriptor to use with classes' custom serializers, creating other kinds is considered experimental for now
      • Replace extensions that returned lists (e.g. elementDescriptors) with properties that return iterable as an optimization
      • IndexOutOfBoundsException in descriptor.getElementDescriptor(index) for List after upgrade to 0.20.0 is fixed (#739)
    • SerializersModule-related API

      • SerialModule is renamed to SerializersModule
      • SerialModuleCollector is renamed to SerializersModuleCollector
      • All builders renamed to be aligned with a single naming scheme (e.g. SerializersModule {} DSL)
      • Deprecate infix with in polymorphic builder in favor of subclass()
      • Helper-like API is extracted to extension functions where possible.
      • polymorphicDefault API for cases when type discriminator is not registered or absent (#902)
    • Contextual serialization

      • @ContextualSerialization is split into two annotations: @Contextual to use on properties and @UseContextualSerialization to use on file
      • New SerialDescriptor.capturedKClass API to introspect SerializersModule-based contextual and polymorphic kinds (#515, #595)
    • Encoding-related API

      • Encoding-related classes (Encoder, Decoder, AbstractEncoder, AbstractDecoder) are moved to a separate kotlinx.serialization.encoding package
      • Deprecated typeParameters argument in beginStructure/beginCollection methods
      • Deprecated updateSerializableValue and similar methods and UpdateMode enum
      • Renamed READ_DONE to DECODE_DONE
      • Make extensions inline where applicable
      • kotlinx.io mockery (InputStream, ByteArrayInput, etc) is removed
    • Serializer-related API

      • UnitSerializer is replaced with Unit.serializer()
      • All methods for serializers retrieval are renamed to serializer
      • Context is used as a fallback in serializer by KType/Java's Reflect Type functions (#902, #903)
      • Deprecated all exceptions except SerializationException.
      • @ImplicitReflectionSerializer is deprecated
      • Support of custom serializers for nullable types is added (#824)

    ProtoBuf

    • ProtoBuf constructor is replaced with ProtoBuf {} builder function
    • ProtoBuf companion object now extends ProtoBuf
    • ProtoId is renamed to ProtoNumber, ProtoNumberType to ProtoIntegerType to be consistent with ProtoBuf specification
    • ProtoBuf performance is significantly (from 2 to 10 times) improved (#216)
    • Top-level primitives, classes and objects are supported in ProtoBuf as length-prefixed tagless messages (#93)
    • SerializationException is thrown instead of IllegalStateException on incorrect input (#870)
    • ProtobufDecodingException is made internal

    Other formats

    • All format constructors are migrated to builder scheme
    • Properties serialize and deserialize enums as strings (#818)
    • CBOR major type 2 (byte string) support (#842)
    • ConfigParser is renamed to Hocon, kotlinx-serialization-runtime-configparser artifact is renamed to kotlinx-serialization-hocon
    • Do not write/read size of collection into Properties' map (#743)
    Source code(tar.gz)
    Source code(zip)
Owner
Kotlin
Kotlin Tools and Libraries
Kotlin
Kotlin tooling for generating kotlinx.serialization serializers for serializing a class as a bitmask

kotlinx-serialization-bitmask Kotlin tooling for generating kotlinx.serialization serializers for serializing a class as a bitmask. Example @Serializa

marie 2 May 29, 2022
Minecraft NBT support for kotlinx.serialization

knbt An implementation of Minecraft's NBT format for kotlinx.serialization. Technical information about NBT can be found here. Using the same version

Ben Woodworth 41 Dec 21, 2022
Android Parcelable support for the Kotlinx Serialization library.

Android Parcelable support for the Kotlinx Serialization library.

Christopher 50 Nov 20, 2022
CSV and FixedLength Formats for kotlinx-serialization

Module kotlinx-serialization-csv Serialize and deserialize ordered CSV and Fixed Length Format Files with kotlinx-serialization. Source code Docs Inst

Philip Wedemann 12 Dec 16, 2022
Type-safe arguments for JetPack Navigation Compose using Kotlinx.Serialization

Navigation Compose Typed Compile-time type-safe arguments for JetPack Navigation Compose library. Based on KotlinX.Serialization. Major features: Comp

Kiwi.com 32 Jan 4, 2023
KotlinX Serialization Standard Serializers (KS3)

KotlinX Serialization Standard Serializers (KS3) This project aims to provide a set of serializers for common types. ⚠️ Consider this project to be Al

Emil Kantis 3 Nov 5, 2022
Kotlinx-murmurhash - Kotlin Multiplatform (KMP) library for hashing using MurmurHash

kotlinx-murmurhash Kotlin Multiplatform (KMP) library for MurmurHash, a non-cryp

Gonçalo Silva 23 Dec 27, 2022
Slime World Format implementation written in Kotlin with Zstd for bukkit.

Slime Korld Easily create many slime worlds with the Slime Korld. What is Slime Korld? Slime Korld is a bukkit library written in Kotlin to make minec

Luiz Otávio 11 Nov 15, 2022
Automatic CoroutineDispatcher injection and extensions for kotlinx.coroutines

Dispatch Utilities for kotlinx.coroutines which make them type-safe, easier to test, and more expressive. Use the predefined types and factories or de

Rick Busarow 132 Dec 9, 2022
Small Kafka Playground to play around with Test Containers, and KotlinX Coroutines bindings while reading Kafka Definite Guide V2

KafkaPlayground Small playground where I'm playing around with Kafka in Kotlin and the Kafka SDK whilst reading the Kafka book Definite Guide from Con

Simon Vergauwen 34 Dec 30, 2022
An tool to help developer to use Retrofit elegantly while using kotlinx.coroutines.

one An tool to help developer to use Retrofit elegantly while using kotlinx.coroutines. Feature Transform different data structs to one. {errorCode, d

ChengTao 30 Dec 27, 2022
Jackson extension for Mojang's NBT format

Jackson NBT Data Format Implements Mojang's NBT format in jackson. Usage Using this format works just like regular jackson, but with the ObjectMapper

Dyescape 3 Sep 10, 2022
Create an application with Kotlin/JVM and Kotlin/JS, and explore features around code sharing, serialization, server- and client

Practical Kotlin Multiplatform on the Web 본 저장소는 코틀린 멀티플랫폼 기반 웹 프로그래밍 워크숍(강좌)을 위해 작성된 템플릿 프로젝트가 있는 곳입니다. 워크숍 과정에서 코틀린 멀티플랫폼을 기반으로 프론트엔드(front-end)는 Ko

SpringRunner 14 Nov 5, 2022
Create an application with Kotlin/JVM and Kotlin/JS, and explore features around code sharing, serialization, server- and client

Building a Full Stack Web App with Kotlin Multiplatform 본 저장소는 INFCON 2022에서 코틀린 멀티플랫폼 기반 웹 프로그래밍 핸즈온랩을 위해 작성된 템플릿 프로젝트가 있는 곳입니다. 핸즈온 과정에서 코틀린 멀티플랫폼을

Arawn Park 19 Sep 8, 2022
Android Spinner Dialog Library supported on both Java and Kotlin, Use for single or multi selection of choice

SpinnerDialog Android Spinner Dialog Library, Use for single or multi selection of choice Android UI Download To include SpinnerDialog in your project

Hamza Khan 55 Sep 15, 2022
A simple Kotlin multi-platform abstraction around the javax.inject annotations.

Inject A simple Kotlin multi-platform abstraction around the javax.inject annotations. This allows using the annotations in Kotlin common code so that

Christopher 43 Aug 17, 2022
A set of highly-opinionated, batteries-included gradle plugins to get you started building delicious multi-module Kotlin projects

Sourdough Gradle What is Sourdough Gradle? Sourdough is a set of highly opinionated gradle plugins that aim to act as the starter for your Kotlin proj

Backbone 0 Oct 3, 2022
Sample application to demonstrate Multi-module Clean MVVM Architecture and usage of Android Hilt, Kotlin Flow, Navigation Graph, Unit tests etc.

MoneyHeist-Chars Sample application to demonstrate Multi-module Clean MVVM Architecture and usage of Android Hilt, Kotlin Flow, Navigation Graph, Room

Hisham 20 Nov 19, 2022
Built with Jetpack compose, multi modules MVVM clean architecture, coroutines + flow, dependency injection, jetpack navigation and other jetpack components

RickAndMortyCompose - Work in progress A simple app using Jetpack compose, clean architecture, multi modules, coroutines + flows, dependency injection

Daniel Waiguru 9 Jul 13, 2022