### Output of collection serialization example Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/formats.md The resulting list representation and the deserialized object output. ```text [kotlinx.serialization, 2, kotlin, jetbrains, 9000] Project(name=kotlinx.serialization, owners=[User(name=kotlin), User(name=jetbrains)], votes=9000) ``` -------------------------------- ### Properties Map Output Example Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/formats.md The output map from serializing the Project data class using the Properties format. Keys are dot-separated to represent nested structures. ```text name = kotlinx.serialization owner.name = kotlin ``` -------------------------------- ### ProtoBuf Schema Output Example Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/formats.md This is the resulting .proto schema text generated from the SampleData Kotlin class. Note the warning about default values not being represented in .proto files. ```text syntax = "proto2"; // serial name 'example.exampleFormats09.SampleData' message SampleData { required int64 amount = 1; optional string description = 2; // WARNING: a default value decoded when value is missing optional string department = 3; } ``` -------------------------------- ### Example Usage of Sequential Encoding and Decoding Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/formats.md Demonstrates the complete cycle of encoding a `Project` data class to a list and then decoding it back, utilizing the custom `ListEncoder` and `ListDecoder` for sequential processing. ```kotlin @Serializable data class Project(val name: String, val owner: User, val votes: Int) @Serializable data class User(val name: String) @OptIn(ExperimentalSerializationApi::class) fun main() { val data = Project("kotlinx.serialization", User("kotlin"), 9000) val list = encodeToList(data) println(list) val obj = decodeFromList(list) println(obj) } ``` -------------------------------- ### Example usage of custom collection serialization Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/formats.md Demonstrates serializing and deserializing a data class containing a list using the custom ListEncoder and ListDecoder. ```kotlin @Serializable data class Project(val name: String, val owners: List, val votes: Int) @Serializable data class User(val name: String) @OptIn(ExperimentalSerializationApi::class) fun main() { val data = Project("kotlinx.serialization", listOf(User("kotlin"), User("jetbrains")), 9000) val list = encodeToList(data) println(list) val obj = decodeFromList(list) println(obj) } ``` -------------------------------- ### Output of external serialization Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/serializers.md The resulting JSON output from the external serializer example. ```text {"name":"kotlinx.serialization","stars":9000} ``` -------------------------------- ### Serialize and Deserialize Data Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/formats.md Example usage of the custom binary encoder and decoder with a serializable data class. ```kotlin @Serializable data class Project(val name: String, val language: String) @OptIn(ExperimentalSerializationApi::class) fun main() { val data = Project("kotlinx.serialization", "Kotlin") val output = ByteArrayOutputStream() encodeTo(DataOutputStream(output), data) val bytes = output.toByteArray() println(bytes.toAsciiHexString()) val input = ByteArrayInputStream(bytes) val obj = decodeFrom(DataInputStream(input)) println(obj) } ``` -------------------------------- ### Example: Serialize and Deserialize Byte Array with Kotlin Serialization Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/formats.md Demonstrates the usage of the custom `DataInputDecoder` to serialize and deserialize a `Project` data class containing a `ByteArray`. It shows the hex string output of the serialized bytes and the deserialized object. ```kotlin @Serializable data class Project(val name: String, val attachment: ByteArray) @OptIn(ExperimentalSerializationApi::class) fun main() { val data = Project("kotlinx.serialization", byteArrayOf(0x0A, 0x0B, 0x0C, 0x0D)) val output = ByteArrayOutputStream() encodeTo(DataOutputStream(output), data) val bytes = output.toByteArray() println(bytes.toAsciiHexString()) val input = ByteArrayInputStream(bytes) val obj = decodeFrom(DataInputStream(input)) println(obj) } ``` -------------------------------- ### Example of Deeply Polymorphic JSON Output Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md Illustrates the JSON output generated from deeply polymorphic data, showing how nested polymorphic types are represented. ```text {"type":"OkResponse","data":{"type":"OwnedProject","name":"kotlinx.serialization","owner":"kotlin"}} OkResponse(data=OwnedProject(name=kotlinx.serialization, owner=kotlin)) ``` -------------------------------- ### Built-in Serializers for Collections Source: https://context7.com/kotlin/kotlinx.serialization/llms.txt Demonstrates serialization of common collection types like List, Set, and Map using the built-in serializers. Requires `kotlinx-serialization-json` for the example output. ```kotlin @Serializable data class Data( val list: List, val set: Set, val map: Map ) fun main() { val data = Data( listOf("a", "b", "c"), setOf(1, 2, 3), mapOf("one" to 1, "two" to 2) ) println(Json.encodeToString(data)) // {"list":["a","b","c"],"set":[1,2,3],"map":{"one":1,"two":2}} } ``` -------------------------------- ### Serialize and Deserialize Polymorphic Data Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md Demonstrates the usage of the merged serializers module by encoding and decoding a polymorphic data structure containing a Project hierarchy. This example requires 'Response' and 'Project' classes to be defined elsewhere. ```kotlin fun main() { // both Response and Project are abstract and their concrete subtypes are being serialized val data: Response = OkResponse(OwnedProject("kotlinx.serialization", "kotlin")) val string = format.encodeToString(data) println(string) println(format.decodeFromString>(string)) } ``` -------------------------------- ### JSON Output for Polymorphic Serialization Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md The resulting JSON string produced by the polymorphic serialization example. ```text {"type":"owned","name":"kotlinx.coroutines","owner":"kotlin"} ``` -------------------------------- ### Define Protobuf oneof message Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/formats.md Example Protobuf message definition containing a oneof field. ```proto message Data { required string name = 1; oneof phone { string home_phone = 2; string work_phone = 3; } } ``` -------------------------------- ### Execute Serialization and Deserialization Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/formats.md Demonstrates the full cycle of encoding a data class to a list and decoding it back to an object. ```kotlin @OptIn(ExperimentalSerializationApi::class) fun main() { val data = Project("kotlinx.serialization", User("kotlin"), 9000) val list = encodeToList(data) println(list) val obj = decodeFromList(list) println(obj) } ``` -------------------------------- ### Serialize and Deserialize with ProtoBuf Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/formats.md Demonstrates basic usage of ProtoBuf.encodeToByteArray and ProtoBuf.decodeFromByteArray with an automatically numbered schema. ```kotlin @Serializable data class Project(val name: String, val language: String) @OptIn(ExperimentalSerializationApi::class) fun main() { val data = Project("kotlinx.serialization", "Kotlin") val bytes = ProtoBuf.encodeToByteArray(data) println(bytes.toAsciiHexString()) val obj = ProtoBuf.decodeFromByteArray(bytes) println(obj) } ``` -------------------------------- ### Json Configuration Options Source: https://context7.com/kotlin/kotlinx.serialization/llms.txt Configure the Json instance to customize behavior such as pretty printing, lenient parsing, and naming strategies. ```kotlin val json = Json { prettyPrint = true // Format output with indentation prettyPrintIndent = " " // Custom indentation isLenient = true // Allow unquoted strings, trailing commas ignoreUnknownKeys = true // Ignore unknown JSON keys coerceInputValues = true // Coerce nulls to defaults encodeDefaults = true // Include default values explicitNulls = false // Omit null values allowStructuredMapKeys = true // Allow complex map keys allowSpecialFloatingPointValues = true // Allow NaN, Infinity classDiscriminator = "type" // Polymorphism discriminator key namingStrategy = JsonNamingStrategy.SnakeCase // Property naming } ``` -------------------------------- ### Serialize Animal Instance Using Custom Module Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md Demonstrates how to use the configured `SerializersModule` with `Json` to serialize an `Animal` instance, which will be dynamically handled by the registered default serializer. ```kotlin val format = Json { serializersModule = module } fun main() { println(format.encodeToString(AnimalProvider.createCat())) } ``` -------------------------------- ### Define Color Serializer Descriptor Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/serializers.md Manually define the structure of the Color class for serialization using buildClassSerialDescriptor. Elements are indexed starting from zero. ```kotlin object ColorAsObjectSerializer : KSerializer { override val descriptor: SerialDescriptor = buildClassSerialDescriptor("my.app.Color") { element("r") element("g") element("b") } ``` -------------------------------- ### Registering a contextual serializer for a generic class Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/serializers.md Demonstrates the difference between registering a fixed serializer instance versus a provider function for generic types. ```kotlin val incorrectModule = SerializersModule { // Can serialize only Box, but not Box or others contextual(BoxSerializer(Int.serializer())) } ``` ```kotlin val correctModule = SerializersModule { // args[0] contains Int.serializer() or String.serializer(), depending on the usage contextual(Box::class) { args -> BoxSerializer(args[0]) } } ``` -------------------------------- ### Define Serializable Event with Duration and Instant Source: https://context7.com/kotlin/kotlinx.serialization/llms.txt Example of defining a data class that includes kotlinx.datetime's Instant and Duration types, requiring them to be marked as @Serializable. ```kotlin import kotlinx.datetime.* import kotlinx.serialization.* import kotlinx.serialization.json.* @Serializable data class Event( val name: String, val timestamp: Instant, val duration: Duration ) ``` -------------------------------- ### Serialize Pair with Custom Class Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/builtin-classes.md The standard library Pair class is serializable. This example shows serializing a Pair where the second element is a custom serializable class. ```kotlin @Serializable class Project(val name: String) fun main() { val pair = 1 to Project("kotlinx.serialization") println(Json.encodeToString(pair)) } ``` -------------------------------- ### Configure Json with a custom module Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/serializers.md Pass the SerializersModule to the Json configuration to enable contextual serialization. ```kotlin val format = Json { serializersModule = module } ``` -------------------------------- ### Define Animal Interfaces and Implementations Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md Defines interfaces for different animal types (Animal, Cat, Dog) and their concrete implementations, along with a provider for creating instances. ```kotlin interface Animal { } interface Cat : Animal { val catType: String } interface Dog : Animal { val dogType: String } private class CatImpl : Cat { override val catType: String = "Tabby" } private class DogImpl : Dog { override val dogType: String = "Husky" } object AnimalProvider { fun createCat(): Cat = CatImpl() fun createDog(): Dog = DogImpl() } ``` -------------------------------- ### Custom JSON Transformation for Polymorphic Deserialization Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/json.md Use JsonTransformingSerializer with @KeepGeneratedSerializer to modify JSON before deserialization. This example renames a JSON key to match a property name for polymorphic types. ```kotlin import kotlinx.serialization.* import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.jsonObject @Serializable sealed class Project { abstract val name: String } @OptIn(ExperimentalSerializationApi::class) @KeepGeneratedSerializer @Serializable(with = BasicProjectSerializer::class) @SerialName("basic") data class BasicProject(override val name: String): Project() object BasicProjectSerializer : JsonTransformingSerializer(BasicProject.generatedSerializer()) { override fun transformDeserialize(element: JsonElement): JsonElement { val jsonObject = element.jsonObject return if ("basic-name" in jsonObject) { val nameElement = jsonObject["basic-name"] ?: throw IllegalStateException() JsonObject(mapOf("name" to nameElement)) } else { jsonObject } } } fun main() { val project = Json.decodeFromString("""{"type":"basic","basic-name":"example"}""") println(project) } ``` -------------------------------- ### Serialize Color class as a string Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/serializers.md Demonstrates basic usage of a custom serializer that maps a Color class to a string representation. ```kotlin val data = Settings(Color(0xffffff), Color(0)) val string = Json.encodeToString(data) println(string) require(Json.decodeFromString(string) == data) } ``` -------------------------------- ### Serialize Unit and Singleton Objects Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/builtin-classes.md Demonstrates serialization of a singleton object and the Unit type. Objects are serialized as empty JSON structures. ```kotlin @Serializable object SerializationVersion { val libraryVersion: String = "1.0.0" } fun main() { println(Json.encodeToString(SerializationVersion)) println(Json.encodeToString(Unit)) } ``` -------------------------------- ### Polymorphic Serialization with Annotation-Defined Discriminator Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/json.md This example shows polymorphic serialization where the class discriminator is defined using the `@JsonClassDiscriminator` annotation on the base class. The discriminator specified in the annotation takes precedence over the `Json` configuration. ```kotlin val format = Json { classDiscriminator = "#class" } fun main() { val data = Message(BaseMessage("not found"), GenericError(404)) println(format.encodeToString(data)) } ``` -------------------------------- ### Include local library in Gradle project Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/building.md Configure repositories and dependencies to use the locally published Kotlin Serialization library. ```gradle repositories { mavenLocal() } dependencies { compile "org.jetbrains.kotlinx:kotlinx-serialization-core:$serialization_version" } ``` -------------------------------- ### Serialize and Deserialize Objects with JSON Source: https://github.com/kotlin/kotlinx.serialization/blob/master/README.md Demonstrates basic usage of the @Serializable annotation and the Json encoder/decoder. ```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(string) println(obj) // Project(name=kotlinx.serialization, language=Kotlin) } ``` -------------------------------- ### Executing polymorphic serialization Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md Demonstrates encoding a sealed interface implementation using the configured SerializersModule. ```kotlin fun main() { val data: Base = Sub1("kotlin") println(format1.encodeToString(data)) println(format2.encodeToString(data)) } ``` -------------------------------- ### Json Configuration Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/serializers.md Documentation for the Json class and its configuration options, including serializers modules. ```APIDOC ## Json Configuration ### Description Configuration and usage of the Json class for JSON serialization and deserialization. ### Classes and Functions - **Json**: Represents a JSON serializer/deserializer instance. - **Json()**: Constructor for creating a Json instance. - **JsonBuilder.serializersModule**: Property to set the serializers module for Json configuration. ### Related Links - [Json]: https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json/index.html - [Json()]: https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json.html - [JsonBuilder.serializersModule]: https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-builder/serializers-module.html ``` -------------------------------- ### Serializers Module Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/serializers.md Documentation for SerializersModule and related components for custom serialization configurations. ```APIDOC ## Serializers Module ### Description Provides a mechanism for configuring custom serializers and managing serialization behavior. ### Classes and Functions - **SerializersModule**: Represents a module containing custom serializers. - **SerializersModule()**: Constructor for creating a SerializersModule. - **SerializersModuleBuilder**: Builder interface for configuring a SerializersModule. - **_contextual**: Function to register a contextual serializer. ### Related Links - [SerializersModule]: https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.modules/-serializers-module/index.html - [SerializersModule()]: https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.modules/-serializers-module.html - [SerializersModuleBuilder]: https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.modules/-serializers-module-builder/index.html - [_contextual]: https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.modules/contextual.html ``` -------------------------------- ### Configure serialization plugin with legacy buildscript Source: https://github.com/kotlin/kotlinx.serialization/blob/master/README.md Use the buildscript block to add the serialization plugin to the classpath for older Gradle configurations. ```kotlin buildscript { repositories { mavenCentral() } dependencies { val kotlinVersion = "2.3.20" classpath(kotlin("gradle-plugin", version = kotlinVersion)) classpath(kotlin("serialization", version = kotlinVersion)) } } ``` ```gradle buildscript { ext.kotlin_version = '2.3.20' repositories { mavenCentral() } dependencies { classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version" } } ``` ```gradle apply plugin: 'kotlin' // or 'kotlin-multiplatform' for multiplatform projects apply plugin: 'kotlinx-serialization' ``` -------------------------------- ### Define serializable class with secondary constructor Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/basic-serialization.md Shows how to use a private primary constructor to satisfy serialization requirements while providing a secondary constructor for custom initialization. ```kotlin @Serializable class Project(path: String) { val owner: String = path.substringBefore('/') val name: String = path.substringAfter('/') } ``` ```kotlin @Serializable class Project private constructor(val owner: String, val name: String) { constructor(path: String) : this( owner = path.substringBefore('/'), name = path.substringAfter('/') ) val path: String get() = "$owner/$name" } ``` ```kotlin fun main() { println(Json.encodeToString(Project("kotlin/kotlinx.serialization"))) } ``` -------------------------------- ### Implement a custom KSerializer using a surrogate Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/serializers.md Implement KSerializer to delegate serialization and deserialization logic to the surrogate class. ```kotlin object ColorSerializer : KSerializer { // Serial names of descriptors should be unique, so we cannot use ColorSurrogate.serializer().descriptor directly override val descriptor: SerialDescriptor = SerialDescriptor("my.app.Color", ColorSurrogate.serializer().descriptor) override fun serialize(encoder: Encoder, value: Color) { val surrogate = ColorSurrogate((value.rgb shr 16) and 0xff, (value.rgb shr 8) and 0xff, value.rgb and 0xff) encoder.encodeSerializableValue(ColorSurrogate.serializer(), surrogate) } override fun deserialize(decoder: Decoder): Color { val surrogate = decoder.decodeSerializableValue(ColorSurrogate.serializer()) return Color((surrogate.r shl 16) or (surrogate.g shl 8) or surrogate.b) } } ``` -------------------------------- ### Convenience Decoding Functions Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/formats.md Provides helper functions to initiate the decoding process from a list of objects. ```kotlin @ExperimentalSerializationApi fun decodeFromList(list: List, deserializer: DeserializationStrategy): T { val decoder = ListDecoder(ArrayDeque(list)) return decoder.decodeSerializableValue(deserializer) } @ExperimentalSerializationApi inline fun decodeFromList(list: List): T = decodeFromList(list, serializer()) ``` -------------------------------- ### Test Nullable Properties with Custom Format Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/formats.md Demonstrates serializing and deserializing data classes with nullable properties using the custom list-based format. ```kotlin @Serializable data class Project(val name: String, val owner: User?, val votes: Int?) @Serializable data class User(val name: String) @OptIn(ExperimentalSerializationApi::class) fun main() { val data = Project("kotlinx.serialization", User("kotlin") , null) val list = encodeToList(data) println(list) val obj = decodeFromList(list) println(obj) } ``` -------------------------------- ### Serialize Color Class to Hex String Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/serializers.md Demonstrates serializing a Color object to its hex string representation using the custom serializer. ```kotlin fun main() { val green = Color(0x00ff00) println(Json.encodeToString(green)) } ``` -------------------------------- ### Define Custom Primitive Serializer for Color Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/serializers.md Implement KSerializer for Color to serialize it as a hex string. Requires implementing serialize, deserialize, and descriptor properties. ```kotlin import kotlinx.serialization.* import kotlinx.serialization.json.* import kotlinx.serialization.encoding.* import kotlinx.serialization.descriptors.* object ColorAsStringSerializer : KSerializer { // Serial names of descriptors should be unique, this is why we advise including app package in the name. override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("my.app.Color", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, value: Color) { val string = value.rgb.toString(16).padStart(6, '0') encoder.encodeString(string) } override fun deserialize(decoder: Decoder): Color { val string = decoder.decodeString() return Color(string.toInt(16)) } } ``` -------------------------------- ### Basic Protocol Buffers Serialization Source: https://context7.com/kotlin/kotlinx.serialization/llms.txt Serializes a data class to Protocol Buffers binary format and deserializes it back. Ensure the `kotlinx-serialization-protobuf` artifact is included. ```kotlin import kotlinx.serialization.* import kotlinx.serialization.protobuf.* @Serializable data class Project(val name: String, val language: String) @OptIn(ExperimentalSerializationApi::class) fun main() { val data = Project("kotlinx.serialization", "Kotlin") val bytes = ProtoBuf.encodeToByteArray(data) val decoded = ProtoBuf.decodeFromByteArray(bytes) println(decoded) // Project(name=kotlinx.serialization, language=Kotlin) } ``` -------------------------------- ### Protobuf Integer Types in Kotlin Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/formats.md Demonstrates the use of @ProtoType with ProtoIntegerType.DEFAULT, SIGNED, and FIXED for Int fields. Use this when optimizing for different integer ranges in Protobuf. ```kotlin @OptIn(ExperimentalSerializationApi::class) @Serializable class Data( @ProtoType(ProtoIntegerType.DEFAULT) val a: Int, @ProtoType(ProtoIntegerType.SIGNED) val b: Int, @ProtoType(ProtoIntegerType.FIXED) val c: Int ) @OptIn(ExperimentalSerializationApi::class) fun main() { val data = Data(1, -2, 3) println(ProtoBuf.encodeToByteArray(data).toAsciiHexString()) } ``` -------------------------------- ### Configure serialization plugin with Gradle plugins DSL Source: https://github.com/kotlin/kotlinx.serialization/blob/master/README.md Use the plugins block to apply the Kotlin serialization plugin alongside the Kotlin compiler plugin. ```kotlin plugins { kotlin("jvm") version "2.3.20" // or kotlin("multiplatform") or any other kotlin plugin kotlin("plugin.serialization") version "2.3.20" } ``` ```gradle plugins { id 'org.jetbrains.kotlin.multiplatform' version '2.3.20' id 'org.jetbrains.kotlin.plugin.serialization' version '2.3.20' } ``` -------------------------------- ### Implement a delegating serializer for Color Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/serializers.md Uses IntArraySerializer to delegate the serialization of a Color class as an IntArray. Requires importing kotlinx.serialization.builtins.IntArraySerializer. ```kotlin import kotlinx.serialization.builtins.IntArraySerializer class ColorIntArraySerializer : KSerializer { private val delegateSerializer = IntArraySerializer() // Serial names of descriptors should be unique, this is why we advise including app package in the name. override val descriptor = SerialDescriptor("my.app.Color", delegateSerializer.descriptor) override fun serialize(encoder: Encoder, value: Color) { val data = intArrayOf( (value.rgb shr 16) and 0xFF, (value.rgb shr 8) and 0xFF, value.rgb and 0xFF ) encoder.encodeSerializableValue(delegateSerializer, data) } override fun deserialize(decoder: Decoder): Color { val array = decoder.decodeSerializableValue(delegateSerializer) return Color((array[0] shl 16) or (array[1] shl 8) or array[2]) } } ``` -------------------------------- ### Pretty Printing JSON Source: https://context7.com/kotlin/kotlinx.serialization/llms.txt Enable prettyPrint in the Json configuration to format output with indentation. ```kotlin val prettyJson = Json { prettyPrint = true } @Serializable data class Project(val name: String, val language: String) fun main() { val data = Project("kotlinx.serialization", "Kotlin") println(prettyJson.encodeToString(data)) // { // "name": "kotlinx.serialization", // "language": "Kotlin" // } ``` -------------------------------- ### Test Array Unwrapping Serialization Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/json.md Test the serialization by encoding a `Project` object containing a single-element user list. The output should be a single JSON object for the user. ```kotlin import kotlinx.serialization.json.Json fun main() { val data = Project("kotlinx.serialization", listOf(User("kotlin"))) println(Json.encodeToString(data)) } ``` -------------------------------- ### Implement ListEncoder for collection support Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/formats.md Extends AbstractEncoder to handle collection sizes by implementing beginCollection. ```kotlin @ExperimentalSerializationApi class ListEncoder : AbstractEncoder() { val list = mutableListOf() override val serializersModule: SerializersModule = EmptySerializersModule() override fun encodeValue(value: Any) { list.add(value) } override fun beginCollection(descriptor: SerialDescriptor, collectionSize: Int): CompositeEncoder { encodeInt(collectionSize) return this } } ``` -------------------------------- ### Merge Serializers Modules for Combined Serialization Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md Combine the 'projectModule' with another module ('responseModule') using the '+' operator to create a unified 'Json' format instance. This allows serialization and deserialization of classes from both hierarchies. ```kotlin val format = Json { serializersModule = projectModule + responseModule } ``` -------------------------------- ### Deserialize Hex String to Color Class Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/serializers.md Shows how to deserialize a hex string back into a Color object using the custom serializer. ```kotlin @Serializable(with = ColorAsStringSerializer::class) class Color(val rgb: Int) fun main() { val color = Json.decodeFromString("\"00ff00\"") println(color.rgb) // prints 65280 } ``` -------------------------------- ### View serialized output Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/formats.md Hexadecimal representation and string output of the serialized Protobuf data. ```text 0a03546f6d1203313233 0a054a657272791a03373839 Data(name=Tom, phone=HomePhone(number=123)) Data(name=Jerry, phone=WorkPhone(number=789)) ``` -------------------------------- ### Encoding and Decoding Interfaces Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/value-classes.md This section details interfaces and methods related to the encoding and decoding process in kotlinx.serialization. ```APIDOC ## CompositeDecoder ### Description Represents a decoder that can handle composite structures like objects and arrays. ### Methods - **decodeInlineElement()**: Decodes an inline element from the composite structure. ## Decoder ### Description An interface for decoding serializable data. ## Encoder ### Description An interface for encoding serializable data. ### Methods - **encodeStructure(descriptor: SerialDescriptor, handler: (CompositeEncoder) -> Unit)**: Encodes a structured element using the provided descriptor and a handler function. - **encodeInline(descriptor: SerialDescriptor)**: Encodes an inline element. - **encodeInt(value: Int)**: Encodes an integer value. ``` -------------------------------- ### View diagnostic output Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/formats.md Diagnostic breakdown of the serialized Protobuf fields. ```text Field #1: 0A String Length = 3, Hex = 03, UTF8 = "Tom" Field #2: 12 String Length = 3, Hex = 03, UTF8 = "123" Field #1: 0A String Length = 5, Hex = 05, UTF8 = "Jerry" Field #3: 1A String Length = 3, Hex = 03, UTF8 = "789" ``` -------------------------------- ### Serialize and Deserialize Generic Box with Project Data Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/serializers.md Demonstrates serializing and deserializing a `Box` containing a `Project` object. The serialization process uses the custom `BoxSerializer`, resulting in JSON that directly represents the `Project` data. ```kotlin @Serializable data class Project(val name: String) fun main() { val box = Box(Project("kotlinx.serialization")) val string = Json.encodeToString(box) println(string) println(Json.decodeFromString>(string)) } ``` -------------------------------- ### Serialize Nested Color Properties Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/serializers.md Illustrates serializing a data class that contains Color properties, utilizing the custom ColorAsStringSerializer. ```kotlin @Serializable(with = ColorAsStringSerializer::class) data class Color(val rgb: Int) @Serializable data class Settings(val background: Color, val foreground: Color) fun main() { val settings = Settings(Color(0x00ff00), Color(0xffffff)) println(Json.encodeToString(settings)) } ``` -------------------------------- ### Bind and Test Custom Color Serializer Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/serializers.md Annotate the Color data class with @Serializable and the custom serializer. Test serialization and deserialization using Json.encodeToString and Json.decodeFromString. ```kotlin @Serializable(with = ColorAsObjectSerializer::class) data class Color(val rgb: Int) fun main() { val color = Color(0x00ff00) val string = Json.encodeToString(color) println(string) require(Json.decodeFromString(string) == color) } ``` -------------------------------- ### Define encodeToList convenience functions Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/formats.md Create top-level functions to simplify the serialization process by wrapping the ListEncoder logic. ```kotlin @ExperimentalSerializationApi fun encodeToList(serializer: SerializationStrategy, value: T): List { val encoder = ListEncoder() encoder.encodeSerializableValue(serializer, value) return encoder.list } ``` ```kotlin @ExperimentalSerializationApi inline fun encodeToList(value: T) = encodeToList(serializer(), value) ``` -------------------------------- ### JSON Output with Custom Class Discriminator Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/json.md This JSON demonstrates the output when a custom class discriminator is used. The discriminator key `"#class"` is included with the serial name of the subclass. ```text {"#class":"owned","name":"kotlinx.coroutines","owner":"kotlin"} ``` -------------------------------- ### Configure pretty printing for JSON output Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/json.md Enable pretty printing by setting the prettyPrint property to true in the Json builder. This adds indentation and line breaks to the serialized output. ```kotlin val format = Json { prettyPrint = true } @Serializable data class Project(val name: String, val language: String) fun main() { val data = Project("kotlinx.serialization", "Kotlin") println(format.encodeToString(data)) } ``` ```text { "name": "kotlinx.serialization", "language": "Kotlin" } ``` -------------------------------- ### Apply Global Naming Strategy Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/json.md Configures a Json instance to automatically transform property names between camelCase and snake_case using JsonNamingStrategy. ```kotlin @Serializable data class Project(val projectName: String, val projectOwner: String) @OptIn(ExperimentalSerializationApi::class) // namingStrategy is an experimental setting for now val format = Json { namingStrategy = JsonNamingStrategy.SnakeCase } fun main() { val project = format.decodeFromString("""{"project_name":"kotlinx.coroutines", "project_owner":"Kotlin"}""") println(format.encodeToString(project.copy(projectName = "kotlinx.serialization"))) } ``` -------------------------------- ### ByteString Class Reference Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/formats.md Reference documentation for the ByteString class, detailing its properties and methods for handling byte sequences in CBOR. ```APIDOC ## ByteString Class ### Description Represents a sequence of bytes, commonly used for binary data within CBOR encoding. ### Endpoint N/A (This is a class reference, not an API endpoint) ### Parameters N/A ### Request Body N/A ### Response N/A ### See Also - [kotlinx.serialization-cbor API documentation](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-cbor/kotlinx.serialization.cbor/-byte-string/index.html) ``` -------------------------------- ### Serialize unsigned types in JSON Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/value-classes.md Demonstrates the use of unsigned types like UByte within serializable classes for JSON output. ```kotlin @Serializable class Counter(val counted: UByte, val description: String) fun main() { val counted = 239.toUByte() println(Json.encodeToString(Counter(counted, "tries"))) } ``` -------------------------------- ### Define Abstract Serializable Hierarchy Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md Demonstrates an attempt to create a serializable hierarchy using an abstract base class, which requires registration in a SerializersModule for polymorphism. ```kotlin @Serializable abstract class Project { abstract val name: String } class OwnedProject(override val name: String, val owner: String) : Project() fun main() { val data: Project = OwnedProject("kotlinx.coroutines", "kotlin") println(Json.encodeToString(data)) } ``` -------------------------------- ### Generating Protocol Buffers Schema Source: https://context7.com/kotlin/kotlinx.serialization/llms.txt Generates the Protocol Buffers schema definition text from serializer descriptors. This is useful for generating `.proto` files. ```kotlin import kotlinx.serialization.protobuf.schema.ProtoBufSchemaGenerator @OptIn(ExperimentalSerializationApi::class) fun main() { val descriptors = listOf(Project.serializer().descriptor) val schema = ProtoBufSchemaGenerator.generateSchemaText(descriptors) println(schema) // syntax = "proto2"; // message Project { // required string name = 1; // required string language = 2; // } } ``` -------------------------------- ### Configure Kotlin and Serialization Versions in Maven Source: https://github.com/kotlin/kotlinx.serialization/blob/master/README.md Define the versions for Kotlin and Kotlinx Serialization in the properties section of your Maven pom.xml. Ensure these versions are compatible. ```xml 2.3.20 1.11.0 ``` -------------------------------- ### Add JSON library dependency Source: https://github.com/kotlin/kotlinx.serialization/blob/master/README.md Include the kotlinx-serialization-json library in your project dependencies. ```kotlin repositories { mavenCentral() } dependencies { implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.11.0") } ``` ```gradle repositories { mavenCentral() } dependencies { implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.11.0" } ``` -------------------------------- ### Implement Color Serialization Logic Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/serializers.md Implement the serialize function using encodeStructure to write Color properties as integers. Ensure elements are encoded in the same order as defined in the descriptor. ```kotlin override fun serialize(encoder: Encoder, value: Color) = encoder.encodeStructure(descriptor) { encodeIntElement(descriptor, 0, (value.rgb shr 16) and 0xff) encodeIntElement(descriptor, 1, (value.rgb shr 8) and 0xff) encodeIntElement(descriptor, 2, value.rgb and 0xff) } ``` -------------------------------- ### Using Custom Response Serializer with Data Class Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/json.md Demonstrates how to serialize and deserialize a list of 'Response' objects, including custom 'Ok' and 'Error' representations, using the previously defined 'ResponseSerializer'. ```kotlin import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json @Serializable data class Project(val name: String) fun main() { val responses = listOf( Response.Ok(Project("kotlinx.serialization")), Response.Error("Not found") ) val string = Json.encodeToString(responses) println(string) println(Json.decodeFromString>>(string)) } ``` -------------------------------- ### Serialize Pairs and Triples with kotlinx.serialization Source: https://context7.com/kotlin/kotlinx.serialization/llms.txt Shows how to serialize Kotlin's built-in Pair and Triple data classes. The default JSON output uses 'first', 'second', and 'third' keys. ```kotlin fun main() { val pair = Pair("key", 42) println(Json.encodeToString(pair)) // {"first":"key","second":42} val triple = Triple("a", "b", "c") println(Json.encodeToString(triple)) // {"first":"a","second":"b","third":"c"} } ``` -------------------------------- ### Serialize properties with backing fields Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/basic-serialization.md Demonstrates that only properties with backing fields are serialized, while getters and delegated properties are ignored. ```kotlin @Serializable class Project( // name is a property with backing field -- serialized var name: String ) { var stars: Int = 0 // property with a backing field -- serialized val path: String // getter only, no backing field -- not serialized get() = "kotlin/$name" var id by ::name // delegated property -- not serialized } fun main() { val data = Project("kotlinx.serialization").apply { stars = 9000 } println(Json.encodeToString(data)) } ``` -------------------------------- ### Construct Serializer for List Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/serializers.md Built-in collection serializers like ListSerializer must be explicitly constructed by providing serializers for their type parameters. Import kotlinx.serialization.builtins for collection serializers. ```kotlin fun main() { val stringListSerializer: KSerializer> = ListSerializer(String.serializer()) println(stringListSerializer.descriptor) } ``` -------------------------------- ### Serializing Interface Instances Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md Once registered, instances of interfaces can be serialized using the configured Json format. ```kotlin fun main() { val data: Project = OwnedProject("kotlinx.coroutines", "kotlin") println(format.encodeToString(data)) } ``` -------------------------------- ### Build JSON Objects Dynamically with DSL Source: https://context7.com/kotlin/kotlinx.serialization/llms.txt Utilize the `buildJsonObject` and related DSL functions to construct JSON objects programmatically. This provides a type-safe way to create complex JSON structures. ```kotlin import kotlinx.serialization.json.* fun main() { val json = buildJsonObject { put("name", "kotlinx.serialization") put("version", 1) putJsonArray("contributors") { add("kotlin") add("jetbrains") } putJsonObject("metadata") { put("stable", true) } } println(json) // {"name":"kotlinx.serialization","version":1,"contributors":["kotlin","jetbrains"],"metadata":{"stable":true}} } ``` -------------------------------- ### Configure ProGuard/R8 for named companion objects Source: https://github.com/kotlin/kotlinx.serialization/blob/master/README.md Rules required to support serialization for classes with named companion objects in Android builds. ```proguard # Serializer for classes with named companion objects are retrieved using `getDeclaredClasses`. # If you have any, 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; } ``` ```proguard # Serializer for classes with named companion objects are retrieved using `getDeclaredClasses`. # If you have any, 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; } # Keep both serializer and serializable classes to save the attribute InnerClasses -keepclasseswithmembers, allowshrinking, allowobfuscation, allowaccessmodification class com.example.myapplication.HasNamedCompanion, # <-- List serializable classes with named companions. com.example.myapplication.HasNamedCompanion2 { *; } ``` -------------------------------- ### Handling Lists as Repeated Fields in Protobuf Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/formats.md Shows how to define lists as repeated fields in Protobuf using Kotlinx.Serialization. Explicitly set default emptyList() for collection properties to ensure correct deserialization of empty lists. ```kotlin @Serializable data class Data( val a: List = emptyList(), val b: List = emptyList() ) @OptIn(ExperimentalSerializationApi::class) fun main() { val data = Data(listOf(1, 2, 3), listOf()) val bytes = ProtoBuf.encodeToByteArray(data) println(bytes.toAsciiHexString()) println(ProtoBuf.decodeFromByteArray(bytes)) } ``` -------------------------------- ### Test the custom encoder with serializable data Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/formats.md Verify the encoder implementation using annotated data classes and the convenience function. ```kotlin @Serializable data class Project(val name: String, val owner: User, val votes: Int) @Serializable data class User(val name: String) @OptIn(ExperimentalSerializationApi::class) fun main() { val data = Project("kotlinx.serialization", User("kotlin"), 9000) println(encodeToList(data)) } ``` -------------------------------- ### Serialize and deserialize data with CBOR Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/formats.md Demonstrates using the Cbor class to encode a serializable data class to a byte array and decode it back. Requires the kotlinx-serialization-cbor module and ExperimentalSerializationApi opt-in. ```kotlin @Serializable data class Project(val name: String, val language: String) @OptIn(ExperimentalSerializationApi::class) fun main() { val data = Project("kotlinx.serialization", "Kotlin") val bytes = Cbor.encodeToByteArray(data) println(bytes.toAsciiHexString()) val obj = Cbor.decodeFromByteArray(bytes) println(obj) } ``` -------------------------------- ### Polymorphic Serialization Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md Details on configuring polymorphic serialization using SerializersModuleBuilder and PolymorphicModuleBuilder. ```APIDOC ## GET /api/users/{id} ### Description Retrieves a specific user resource by their unique identifier. ### Method GET ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the user to retrieve. #### Query Parameters - **fields** (string) - Optional - Comma-separated list of fields to include in the response. ### Response #### Success Response (200) - **id** (integer) - The unique identifier for the user. - **name** (string) - The name of the user. - **email** (string) - The email address of the user. #### Response Example { "id": 123, "name": "John Doe", "email": "john.doe@example.com" } ``` -------------------------------- ### Output of Nullable Property Serialization Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/formats.md The resulting list representation and deserialized object output. ```text [kotlinx.serialization, !!, kotlin, NULL] Project(name=kotlinx.serialization, owner=User(name=kotlin), votes=null) ``` -------------------------------- ### Specify Serializers for a File Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/serializers.md Use the `@file:UseSerializers` annotation at the beginning of a source file to specify a serializer for a particular type throughout the entire file. This eliminates the need for repeated annotations on individual properties or types. ```kotlin @file:UseSerializers(DateAsLongSerializer::class) ``` ```kotlin object DateAsLongSerializer : KSerializer { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("my.app.DateAsLong", PrimitiveKind.LONG) override fun serialize(encoder: Encoder, value: Date) = encoder.encodeLong(value.time) override fun deserialize(decoder: Decoder): Date = Date(decoder.decodeLong()) } ``` ```kotlin @Serializable class ProgrammingLanguage(val name: String, val stableReleaseDate: Date) fun main() { val data = ProgrammingLanguage("Kotlin", SimpleDateFormat("yyyy-MM-ddX").parse("2016-02-15+00")) println(Json.encodeToString(data)) } ``` -------------------------------- ### Serialize data with a custom format Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/serializers.md Use the configured Json instance to serialize objects containing contextual properties. ```kotlin fun main() { val data = ProgrammingLanguage("Kotlin", SimpleDateFormat("yyyy-MM-ddX").parse("2016-02-15+00")) println(format.encodeToString(data)) } ``` -------------------------------- ### Create Custom Serializer Source: https://context7.com/kotlin/kotlinx.serialization/llms.txt Implement KSerializer to define custom serialization logic for types that do not have built-in support. ```kotlin import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* object ColorAsStringSerializer : KSerializer { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Color", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, value: Color) { encoder.encodeString("${value.r},${value.g},${value.b}") } override fun deserialize(decoder: Decoder): Color { val parts = decoder.decodeString().split(",") return Color(parts[0].toInt(), parts[1].toInt(), parts[2].toInt()) } } data class Color(val r: Int, val g: Int, val b: Int) @Serializable data class Project( val name: String, @Serializable(with = ColorAsStringSerializer::class) val color: Color ) fun main() { val data = Project("kotlinx.serialization", Color(255, 128, 0)) println(Json.encodeToString(data)) // {"name":"kotlinx.serialization","color":"255,128,0"} } ``` -------------------------------- ### Serialize Interfaces with Polymorphism Source: https://context7.com/kotlin/kotlinx.serialization/llms.txt Define an interface and its serializable implementations. Use `SerializersModule` to register the interface and its concrete classes for polymorphic serialization. ```kotlin import kotlinx.serialization.modules.* interface Project { val name: String } @Serializable @SerialName("owned") class OwnedProject(override val name: String, val owner: String) : Project val module = SerializersModule { polymorphic(Project::class) { subclass(OwnedProject::class) } } val format = Json { serializersModule = module } fun main() { val data: Project = OwnedProject("kotlinx.serialization", "kotlin") println(format.encodeToString(data)) } ``` -------------------------------- ### Encoder and Decoder Interfaces Source: https://github.com/kotlin/kotlinx.serialization/blob/master/docs/serializers.md Documentation for the core Encoder and Decoder interfaces used in kotlinx.serialization for encoding and decoding data structures. ```APIDOC ## Encoder and Decoder Interfaces ### Description Provides interfaces for encoding and decoding serializable values. ### Interfaces #### Encoder - **encodeSerializableValue**: Encodes a serializable value. - **encodeStructure**: Encodes a structured serializable value. #### Decoder - **decodeString**: Decodes a string value. - **decodeSerializableValue**: Decodes a serializable value. ### Related Links - [Decoder]: https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.encoding/-decoder/index.html - [Encoder.encodeSerializableValue]: https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.encoding/-encoder/encode-serializable-value.html - [Decoder.decodeSerializableValue]: https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.encoding/-decoder/decode-serializable-value.html - [encodeStructure]: https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.encoding/encode-structure.html ```