Demo project for all the features implemented in the Kotlin serialization prototype.
You need to obtain compiler plugin to work with Kotlin serialization prototype.
IDEA Kotlin plugin for Kotlin 1.1.2 with serialization:
- Make sure you have IntelliJ IDEA 2017.1 installed
- Download
plugin/kotlin-plugin-1.1.2-serialization.zip
. - In IDEA go to Settings > Plugins > Install plugin from disk ... and select this file.
The command-line compiler plugin for Kotlin 1.1.2 is available in the lib
subdirectory.
Use serialization plugin with kotlin compiler using the following command-line options:
kotlinc -Xplugin kotlin-serialization-compiler.jar \
-cp kotlin-serialization-runtime.jar ...
The plugin for building Gradle project with is is available in the lib
subdirectory.
See build.gradle
as example on how to use it. You need to add the following compiler
configuration option to your build file:
compileKotlin {
kotlinOptions.freeCompilerArgs += ["-Xplugin", "lib/kotlin-serialization-gradle.jar"]
}
In addition to that, if you are configuring Kotlin in your Gradle project using "old style"
apply plugin: 'kotlin'
line,
then you also need to add serialization plugin to classpath in buildscript
section:
buildscript {
dependencies {
classpath files("lib/kotlin-serialization-gradle.jar")
}
}
However, you don't need buildscript
classpath if Kotlin is configured with Gradle plugin DSL like this:
plugins {
id "org.jetbrains.kotlin.jvm" version "1.1.2"
}
Define serializable class with @Serializable
annotation. For example:
@Serializable
data class Product(val name: String, val price: Double)
A few rules to follow:
- It does not have to be data-class.
- It must have
val
/var
constructor parameters (simple constructor parameters are not supported yet) - All properties in class body must be
var
(val
properties are not supported yet) - Generic classes cannot be serializable yet, but all standard collections are supported.
Now, you can convert the instance of this class to JSON with:
val str = JSON.stringify(Product("IntelliJ IDEA Ultimate", 199.0))
and parse the JSON string back into an instance with:
val obj = JSON.parse<Product>(str)
You can define your own serialization formats with a bit of library code:
- See MapIO for a sample on how to convert an object to/from map.
- See MapNullableIO for the same as above with support for nullable types.
- See DataBinaryNullableIO for a simple binary format implementation.
- See KeyValueIO for a simple JSON-like format implementation.
This project contains a test with serialization of various complex data structures with different formats. Run it using the following command:
gradlew test
You should get "BUILD SUCCESSFUL" line at the end:
See https://github.com/JetBrains/kotlin/tree/rr/elizarov/kotlin-serialization
Build prototype with
ant dist -Dkotlin-serialization=true