CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-jetbrains-kotlinx--kotlinx-serialization-core-jvm

Kotlin multiplatform serialization runtime library core module with JVM target support

Pending
Overview
Eval results
Files

core-serialization.mddocs/

Core Serialization

The fundamental serialization interfaces and functions that define how Kotlin objects are converted to and from various serialized formats. This includes the main serialization strategy interfaces, serializer lookup functions, format interfaces, and polymorphic serialization support.

Capabilities

Core Interfaces

The foundation interfaces that define serialization behavior for any type.

/**
 * The main serialization interface combining both serialization and deserialization strategies.
 * Every serializable type has an associated KSerializer that handles conversion to/from formats.
 */
interface KSerializer<T> : SerializationStrategy<T>, DeserializationStrategy<T> {
    override val descriptor: SerialDescriptor
}

/**
 * Defines the serialization process for converting objects to their serial form.
 * Contains the structural description and serialization logic.
 */
interface SerializationStrategy<in T> {
    val descriptor: SerialDescriptor
    fun serialize(encoder: Encoder, value: T)
}

/**
 * Defines the deserialization process for converting serial form back to objects.
 * Contains the structural description and deserialization logic.
 */
interface DeserializationStrategy<out T> {
    val descriptor: SerialDescriptor
    fun deserialize(decoder: Decoder): T
}

Usage Examples:

import kotlinx.serialization.*
import kotlinx.serialization.json.*

@Serializable
data class User(val name: String, val age: Int)

// Get the generated serializer
val userSerializer: KSerializer<User> = User.serializer()

// Use it directly with format
val json = Json.encodeToString(userSerializer, User("Alice", 25))
val user = Json.decodeFromString(userSerializer, json)

Serializer Lookup Functions

Functions for obtaining serializers at runtime, including type-safe and reflection-based approaches.

/**
 * Retrieves a serializer for the given reified type T.
 * This is the primary way to get serializers for known types at compile time.
 */
inline fun <reified T> serializer(): KSerializer<T>

/**
 * Creates a serializer for the given KType.
 * Useful for runtime serializer resolution when type information is dynamic.
 * @param type The KType to create a serializer for
 * @return KSerializer for the specified type
 * @throws SerializationException if serializer cannot be created
 */
fun serializer(type: KType): KSerializer<Any?>

/**
 * Creates a serializer for the given KType, returning null if not possible.
 * Safe variant that doesn't throw exceptions on failure.
 * @param type The KType to create a serializer for  
 * @return KSerializer for the type, or null if unavailable
 */
fun serializerOrNull(type: KType): KSerializer<Any?>?

/**
 * JVM-specific: Creates a serializer for the given Java Type.
 * Provides Java interoperability for runtime serializer resolution.
 * @param type The Java Type to create a serializer for
 * @return KSerializer for the specified Java type (non-nullable)
 * @throws SerializationException if serializer cannot be created
 */
fun serializer(type: java.lang.reflect.Type): KSerializer<Any>

/**
 * JVM-specific: Creates a serializer for the given Java Type, returning null if not possible.
 * Safe variant for Java Type serializer resolution.
 * @param type The Java Type to create a serializer for
 * @return KSerializer for the type, or null if unavailable (non-nullable)
 */
fun serializerOrNull(type: java.lang.reflect.Type): KSerializer<Any>?

Usage Examples:

import kotlinx.serialization.*
import kotlin.reflect.typeOf

// Compile-time serializer lookup (preferred)
val stringSerializer = serializer<String>()
val listSerializer = serializer<List<Int>>()

// Runtime serializer lookup
val userType = typeOf<User>()
val userSerializer = serializer(userType) as KSerializer<User>

// Safe runtime lookup
val maybeSerializer = serializerOrNull(typeOf<SomeClass>())
if (maybeSerializer != null) {
    // Use serializer
}

// JVM-specific: Java Type serialization
import java.lang.reflect.Type

val javaType: Type = User::class.java
val javaSerializer = serializer(javaType) as KSerializer<User>

// Safe Java Type lookup
val maybejavaSerializer = serializerOrNull(javaType)

Format Interfaces

Base interfaces that serialization formats implement to provide encoding/decoding capabilities.

/**
 * Base interface for all serialization formats.
 * Provides access to the serializers module for custom serializer resolution.  
 */
interface SerialFormat {
    val serializersModule: SerializersModule
}

/**
 * Serialization format that converts objects to/from strings.
 * Implemented by text-based formats like JSON, XML, YAML.
 */
interface StringFormat : SerialFormat {
    fun <T> encodeToString(serializer: SerializationStrategy<T>, value: T): String
    fun <T> decodeFromString(deserializer: DeserializationStrategy<T>, string: String): T
}

/**
 * Serialization format that converts objects to/from byte arrays.
 * Implemented by binary formats like ProtoBuf, CBOR, MessagePack.
 */
interface BinaryFormat : SerialFormat {
    fun <T> encodeToByteArray(serializer: SerializationStrategy<T>, value: T): ByteArray
    fun <T> decodeFromByteArray(deserializer: DeserializationStrategy<T>, bytes: ByteArray): T
}

Format Extension Functions

Convenient extension functions that provide reified type parameter support for format operations.

/**
 * Encodes the given value to string using reified type parameter.
 * @param value The value to encode
 * @return Encoded string representation
 */
inline fun <reified T> StringFormat.encodeToString(value: T): String

/**
 * Decodes a string to the specified type using reified type parameter.
 * @param string The string to decode
 * @return Decoded value of type T
 */
inline fun <reified T> StringFormat.decodeFromString(string: String): T

/**
 * Encodes the given value to byte array using reified type parameter.
 * @param value The value to encode  
 * @return Encoded byte array
 */
inline fun <reified T> BinaryFormat.encodeToByteArray(value: T): ByteArray

/**
 * Decodes a byte array to the specified type using reified type parameter.
 * @param bytes The byte array to decode
 * @return Decoded value of type T
 */
inline fun <reified T> BinaryFormat.decodeFromByteArray(bytes: ByteArray): T

/**
 * Encodes the given value to hex string representation using BinaryFormat.
 * @param value The value to encode
 * @return Hex string representation of encoded bytes
 */
inline fun <reified T> BinaryFormat.encodeToHexString(value: T): String

/**
 * Decodes a hex string to the specified type using BinaryFormat.
 * @param hex The hex string to decode
 * @return Decoded value of type T
 */
inline fun <reified T> BinaryFormat.decodeFromHexString(hex: String): T

Usage Examples:

import kotlinx.serialization.*
import kotlinx.serialization.json.*

val json = Json

@Serializable  
data class Person(val name: String, val age: Int)

val person = Person("Bob", 30)

// Using extension functions (preferred)
val jsonString = json.encodeToString(person)
val decoded = json.decodeFromString<Person>(jsonString)

// Using format interface directly
val jsonString2 = json.encodeToString(Person.serializer(), person)
val decoded2 = json.decodeFromString(Person.serializer(), jsonString2)

Polymorphic Serializers

Specialized serializers for handling polymorphic types and runtime type resolution.

/**
 * Provides multiplatform polymorphic serialization for open classes, interfaces, and abstract classes.
 * Used when the actual runtime type needs to be preserved during serialization.
 */
class PolymorphicSerializer<T : Any>(val baseClass: KClass<T>) : AbstractPolymorphicSerializer<T>()

/**
 * Provides polymorphic serialization specifically for sealed classes.
 * Optimized for sealed class hierarchies with compile-time known subclasses.
 */
class SealedClassSerializer<T : Any>(
    serialName: String,
    val baseClass: KClass<T>,
    subclassSerializers: Array<KSerializer<out T>>
) : AbstractPolymorphicSerializer<T>()

/**
 * Provides runtime serializer retrieval from SerializersModule instead of compile-time resolution.
 * Used with @Contextual annotation for types that need runtime serializer lookup.
 */
class ContextualSerializer<T : Any>(
    val serializerClass: KClass<T>,
    val fallbackSerializer: KSerializer<T>? = null
) : KSerializer<T>

Usage Examples:

import kotlinx.serialization.*
import kotlinx.serialization.json.*
import kotlinx.serialization.modules.*

// Sealed class serialization
@Serializable
sealed class Result {
    @Serializable
    data class Success(val data: String) : Result()
    
    @Serializable
    data class Error(val message: String) : Result()
}

// Polymorphic interface serialization  
@Serializable
@JsonClassDiscriminator("type")
sealed interface Animal {
    @Serializable
    @SerialName("dog")
    data class Dog(val breed: String) : Animal
    
    @Serializable
    @SerialName("cat") 
    data class Cat(val indoor: Boolean) : Animal
}

// Contextual serialization for external types
val module = SerializersModule {
    contextual(UUID::class, UUIDSerializer)
}

val json = Json { serializersModule = module }

@Serializable
data class Document(
    @Contextual val id: UUID,
    val title: String
)

Exception Classes

/**
 * Generic exception for serialization and deserialization problems.
 * Base class for all serialization-related exceptions.
 */
open class SerializationException(
    message: String? = null, 
    cause: Throwable? = null
) : IllegalArgumentException(message, cause)

/**
 * Thrown when a KSerializer didn't receive a non-optional property during deserialization.
 * Indicates missing required fields in the input data.
 */
class MissingFieldException(
    val fieldName: String, 
    val serialName: String = fieldName
) : SerializationException(
    "Field '$fieldName' is required for type with serial name '$serialName', but it was missing"
)

Error Handling

Common serialization errors and their typical causes:

  • SerializationException: General serialization failures, often due to format incompatibilities
  • MissingFieldException: Required fields missing from input data
  • IllegalArgumentException: Invalid serializer configurations or malformed data
  • ClassCastException: Type mismatches during polymorphic deserialization

Install with Tessl CLI

npx tessl i tessl/maven-org-jetbrains-kotlinx--kotlinx-serialization-core-jvm

docs

annotations.md

built-ins.md

core-serialization.md

descriptors.md

encoding.md

index.md

modules.md

tile.json