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 {
implementation("org.jetbrains.kotlinx:
kotlinx-serialization-json:$serializationVersion")
@Serializable
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 =
encodeToString(
serializersModule.serializer(),
value)
@Serializable
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
@Serializable
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"
}
println(Json.encodeToString(
Json.decodeFromString<Set<Int>>("[1, 1, 2]")
))
println(Json.encodeToString(
Json.decodeFromString<List<Int>>("[1, 1, 2]")
))
[1,2]
[1,1,2]
@Serializable
data class Group(
val name: String,
val students: List<Student>,
)
println(Json.encodeToString(mapOf(1 to leonard, 2 to sheldon)))
println(
(Json { allowStructuredMapKeys = true })
.encodeToString(mapOf(leonard to 1, sheldon to 2))
)
{"1":{"name":"Leonard"},"2":{"name":"Sheldon"}}
[{"name":"Leonard"},1,{"name":"Sheldon"},2]