%2522%26replace%3D%25241%26label%3DKotlin%26color%3Dgreen%26link%3Dhttps%253A%252F%252Fkotlinlang.org%252F)
net.akehurst.kotlin.kserialisation
A Kotlin Multiplatform library for serialising Kotlin object graphs to JSON or HJSON and back again,
including graphs that contain shared objects and references (cycles).
Unlike annotation or compiler-plugin based serialisers, kserialisation is driven by a type model that describes your classes,
which properties are composite (owned, written in full) and which are references (written as a pointer to an object that is
written elsewhere in the same document). The object graph is walked using the
komposite walker (net.akehurst.language:kotlinx-komposite), and objects are re-created on read using
net.akehurst.kotlinx:kotlinx-reflect.
Features:
- JSON and HJSON formats, with the same model and API
- composite vs. reference properties, so object graphs with back-references and cycles round-trip
- an object that is met more than once (by identity) is written once in full and as a
$ref elsewhere
- user-defined primitive mappings (e.g.
kotlin.time.Instant as epoch millis)
Modules
The kserialisation-bytes folder is an unfinished binary format and is not currently part of the build.
Getting it
Releases are published to Maven Central under the group net.akehurst.kotlin.kserialisation
(see the Maven Central badge above for the latest version).
kotlin {
sourceSets {
commonMain.dependencies {
implementation("net.akehurst.kotlin.kserialisation:kserialisation-json:<version>")
implementation("net.akehurst.kotlin.kserialisation:kserialisation-hjson:<version>")
}
}
}
The type model DSL (typesDomain { ... }) comes from net.akehurst.language:agl-processor, and class registration
(KotlinxReflect) from net.akehurst.kotlinx:kotlinx-reflect; add those as dependencies if you configure the serialiser from your own code.
Usage
1. Describe your types
Given some classes:
package com.example
enum class Colour { RED, GREEN, BLUE }
class Node(
val name: String,
var child: Node?
) {
var parent: Node? = null
var size: Int = -1
}
create a serialiser and give it a type model. CMP marks a composite (owned) property, REF a reference;
VAL/VAR mark whether the property is read-only or mutable. Constructor parameters tell the serialiser how to
create an instance when reading.
2. Write and read
val root = Node("root", Node("leaf", null))
root.size = 5
root.child?.parent = root
val jsonText: String = serialiser.toJson(root, root).toFormattedJsonString(" ", " ")
copy: Node = serialiser.toData(jsonText)
check(copy.child?.parent === copy)
The JSON produced looks like this (the shape is the same for HJSON, written with HJSON syntax):
Boolean and String are written as plain JSON values; other numeric types are written as $PRIMITIVE objects so that
their exact Kotlin type is preserved.
For HJSON use KSerialiserHJson in the same way, with toHJson(root, data) and toHJsonString():
val serialiser = KSerialiserHJson()
val hjsonText = serialiser.toHJson(root, root).toHJsonString()
val copy: Node = serialiser.toData(hjsonText)
Custom primitives
Register a mapping for any type declared as a primitive in the type model:
serialiser.registerPrimitiveAsObject(
Instant::class,
{ value -> JsonNumber(value.toEpochMilliseconds().toString()) },
{ json -> Instant.fromEpochMilliseconds(json.asNumber().toLong()) }
)
registerPrimitiveAsObject writes the value wrapped in a $PRIMITIVE object (keeping its type name);
registerPrimitive writes the raw JSON value only.
Lookups
Objects that already exist when the data is read (for example, built-in definitions) can be written by a key instead of
in full, and resolved to the existing instance on read:
import net.akehurst.kotlinx.komposite.common.LookupMapper
serialiser.registry.registerLookup(LookupMapper(
name = "known",
toKey = { v -> if (v === knownInstance) "the-known-one" else null },
fromKey = { k -> if (k == "the-known-one") knownInstance else null }
))
Such objects are written as { "$kind" : "$LOOKUP", "$class" : "known", "$value" : "the-known-one" }.
Format reference
References use the JSON Reference form: # followed by a JSON Pointer (RFC 6901). When reading, the form
/a/b, written by earlier versions of the JSON format, is also accepted.
Objects are compared by identity: two distinct but equal objects are both written in full.
A cycle of composite properties that passes through constructor arguments cannot be re-created and gives a
KSerialiserJsonException on read.
Building
The Gradle build is in the net.akehurst.kotlin.kserialisation sub-folder:
cd net.akehurst.kotlin.kserialisation
./gradlew build
Requirements: a JDK 17 or newer. Versions of Kotlin and dependencies are in
gradle/libs.versions.toml.
Snapshot versions of the net.akehurst.* dependencies are resolved from mavenLocal(), so when the build uses
-SNAPSHOT dependencies they must be built and published locally first (./gradlew publishToMavenLocal in their repositories).
License
Apache License 2.0, see LICENSE.txt.