Kotlin multiplatform / multi-format reflectionless serialization

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.


plugins {
    kotlin("jvm") version "1.8.0"
    kotlin("plugin.serialization") version "1.8.0"
val serializationVersion = "1.5.0-RC"
dependencies {

Простая сериализация

data class Student (val name: String)

val sheldon = Student("Sheldon")
val sheldonJson = Json.encodeToString(
    Student.serializer(), sheldon)
val leonardJson = sheldonJson.replace("Sheldon", "Leonard")
val leonard = Json.decodeFromString(
    Student.serializer(), leonardJson)

Подбор сериализатора

val sheldonJson = Json.encodeToString(sheldon)
val leonardJson = sheldonJson.replace("Sheldon", "Leonard")
val leonard = Json.decodeFromString<Student>(leonardJson)
public inline fun <reified T> StringFormat.encodeToString(
    value: T): String =

Конструкторы при сериализации

class Person (name: String){
    val firstname=    name.substringBefore(" ")
    val surname =     name.substringAfter(" ")
    val name: String
        get() = "$firstname $surname"
Error:This class is not serializable automatically because it has primary constructor parameters that are not properties

Конструкторы при сериализации

data class Person private constructor(
    val firstname: String,
    val surname: String
) {
    constructor(name: String) : this(
        name.substringBefore(" "),
        name.substringAfter(" ")

    val name: String
        get() = "$firstname $surname"

Массивы, списки, множества

    Json.decodeFromString<Set<Int>>("[1, 1, 2]")
    Json.decodeFromString<List<Int>>("[1, 1, 2]")


Сериализация вложенных объектов

data class Group(
    val name: String,
    val students: List<Student>,

Сериализация карт

println(Json.encodeToString(mapOf(1 to leonard, 2 to sheldon)))
    (Json { allowStructuredMapKeys = true })
        .encodeToString(mapOf(leonard to 1, sheldon to 2))