or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/maven-io-ktor--ktor-client-serialization

Kotlinx Serialization support for Ktor HTTP Client, providing JSON serialization and deserialization capabilities for data classes marked with @Serializable annotation.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/io.ktor/ktor-client-serialization@3.2.x

To install, run

npx @tessl/cli install tessl/maven-io-ktor--ktor-client-serialization@3.2.0

index.mddocs/

Ktor Client Serialization

Ktor Client Serialization provides Kotlinx Serialization support for the Ktor HTTP Client, enabling automatic JSON serialization and deserialization of data classes marked with @Serializable annotation. This package implements a deprecated JsonSerializer that was part of the legacy JSON plugin system.

Note: This package is deprecated with DeprecationLevel.ERROR and has been superseded by the ContentNegotiation plugin with kotlinx.serialization converters. Users should migrate to the modern ContentNegotiation approach.

Package Information

  • Package Name: ktor-client-serialization
  • Package Type: maven
  • Language: Kotlin (multiplatform)
  • Installation: Add to build.gradle.kts:
    implementation("io.ktor:ktor-client-serialization:3.2.0")

Core Imports

import io.ktor.client.plugins.kotlinx.serializer.KotlinxSerializer
import kotlinx.serialization.json.Json

Basic Usage

import io.ktor.client.plugins.kotlinx.serializer.KotlinxSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

// Define a serializable data class
@Serializable
data class User(val name: String, val age: Int)

// Create serializer with default configuration
val serializer = KotlinxSerializer()

// Or with custom Json configuration
val customJson = Json {
    ignoreUnknownKeys = true
    isLenient = true
}
val customSerializer = KotlinxSerializer(customJson)

// Use with legacy JSON plugin (deprecated)
// HttpClient {
//     install(JsonFeature) {
//         serializer = KotlinxSerializer()
//     }
// }

Architecture

The package is built around the following key components:

  • KotlinxSerializer: Main serializer class implementing the JsonSerializer interface
  • Json Configuration: Configurable JSON processing with kotlinx.serialization
  • Multiplatform Support: Platform-specific initialization for JVM, JS, Native, and WebAssembly
  • Type Detection: Automatic serialization strategy selection based on data types
  • Legacy Integration: Compatibility with the deprecated JSON plugin system

Capabilities

JSON Serialization

The KotlinxSerializer class provides JSON serialization and deserialization capabilities for Kotlin data classes.

/**
 * A JsonSerializer implemented for kotlinx Serializable classes.
 * 
 * @deprecated Please use ContentNegotiation plugin and its converters
 */
@Deprecated(
    "Please use ContentNegotiation plugin and its converters: https://ktor.io/docs/migration-to-20x.html#serialization-client",
    level = DeprecationLevel.ERROR
)
class KotlinxSerializer(
    private val json: Json = DefaultJson
) : JsonSerializer {
    
    /**
     * Convert data object to OutgoingContent with specified content type.
     */
    fun write(data: Any, contentType: ContentType): OutgoingContent
    
    /**
     * Convert data object to OutgoingContent with default JSON content type.
     */
    fun write(data: Any): OutgoingContent
    
    /**
     * Read content from response using information specified in type.
     */
    fun read(type: TypeInfo, body: Input): Any
    
    
    companion object {
        /**
         * Default Json configuration for KotlinxSerializer.
         */
        val DefaultJson: Json
    }
}

Usage Examples:

import io.ktor.client.plugins.kotlinx.serializer.KotlinxSerializer
import io.ktor.http.ContentType
import io.ktor.util.reflect.typeInfo
import io.ktor.utils.io.core.ByteReadPacket
import kotlinx.serialization.Serializable

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

val serializer = KotlinxSerializer()

// Serialize data to OutgoingContent
val person = Person("Alice", "alice@example.com")
val content = serializer.write(person, ContentType.Application.Json)

// Deserialize from Input (using ktor Input type)
val jsonBytes = """{"name":"Bob","email":"bob@example.com"}""".toByteArray()
val jsonInput = ByteReadPacket(jsonBytes)
val deserializedPerson = serializer.read(typeInfo<Person>(), jsonInput) as Person

Write Operations

Serializes Kotlin objects to JSON format as OutgoingContent.

/**
 * Convert data object to OutgoingContent with specified content type.
 * @param data The object to serialize
 * @param contentType The content type for the output
 * @return OutgoingContent containing the serialized JSON
 */
fun write(data: Any, contentType: ContentType): OutgoingContent

Read Operations

Deserializes JSON content to Kotlin objects using type information.

/**
 * Read content from response using information specified in type.
 * @param type TypeInfo containing the target type information
 * @param body Input stream containing JSON data
 * @return Deserialized object of the specified type
 */
fun read(type: TypeInfo, body: Input): Any

Default Configuration

Provides a default Json configuration optimized for Ktor client usage.

/**
 * Default Json configuration for KotlinxSerializer.
 */
val DefaultJson: Json

The default configuration includes:

  • isLenient = false - Strict JSON parsing
  • ignoreUnknownKeys = false - Fail on unknown properties
  • allowSpecialFloatingPointValues = true - Support for NaN and Infinity
  • useArrayPolymorphism = false - Use object-based polymorphic serialization

Platform Initialization

Each platform provides automatic initialization for the serializer registry.

/**
 * Platform-specific eager initialization object that registers KotlinxSerializer.
 * Available on JS, POSIX (Native), and WebAssembly platforms.
 */
@OptIn(ExperimentalStdlibApi::class)
@InternalAPI
@EagerInitialization
object SerializerInitializer

The initialization ensures that KotlinxSerializer is automatically available in the platform-specific serializer stores/registries without manual registration.

Types

/**
 * Base interface for JSON serializers in Ktor client.
 */
@Deprecated(
    "Please use ContentNegotiation plugin and its converters",
    level = DeprecationLevel.ERROR
)
interface JsonSerializer {
    fun write(data: Any, contentType: ContentType): OutgoingContent
    fun write(data: Any): OutgoingContent
    fun read(type: TypeInfo, body: Input): Any
}

/**
 * Content type for HTTP requests and responses.
 */
class ContentType {
    companion object {
        object Application {
            val Json: ContentType
        }
    }
}

/**
 * Type information for deserialization.
 */
class TypeInfo

/**
 * Input interface for reading data from ktor.utils.io.core.
 */
interface Input

/**
 * Content that can be sent in HTTP requests.
 */
interface OutgoingContent

/**
 * Kotlinx Serialization Json configuration.
 * From kotlinx.serialization.json package.
 */
class Json {
    val isLenient: Boolean
    val ignoreUnknownKeys: Boolean
    val allowSpecialFloatingPointValues: Boolean
    val useArrayPolymorphism: Boolean
    val serializersModule: SerializersModule
    
    companion object {
        operator fun invoke(builderAction: JsonBuilder.() -> Unit): Json
    }
}

/**
 * Kotlinx Serialization serializers module.
 */
class SerializersModule

Supported Types

The serializer automatically handles:

  • @Serializable data classes: Primary use case with full type safety
  • Collections: List, Set, Array with element type detection
  • Maps: Map<K,V> with serializable keys and values
  • Primitive types: String, Int, Long, Float, Double, Boolean
  • JsonElement types: Direct kotlinx.serialization JSON elements
  • Nullable types: Optional values with proper null handling
  • Polymorphic types: With proper serialization configuration

Error Handling

The serializer may throw exceptions in the following cases:

  • SerializationException: When serialization/deserialization fails due to incompatible data structures or missing @Serializable annotations
  • IllegalArgumentException: When collections contain mixed element types. Actual error message: "Serializing collections of different element types is not yet supported. Selected serializers: [list of serializer names]"
  • JsonDecodingException: When JSON parsing fails due to malformed JSON or invalid syntax
  • ClassCastException: When type information doesn't match actual data during deserialization
  • Error: For mixed collection element types that cannot be unified under a single serializer

Migration Guide

This package is deprecated. Migrate to ContentNegotiation:

Old approach (deprecated):

HttpClient {
    install(JsonFeature) {
        serializer = KotlinxSerializer()
    }
}

New approach (recommended):

HttpClient {
    install(ContentNegotiation) {
        json(Json {
            ignoreUnknownKeys = true
        })
    }
}

For detailed migration instructions, see: https://ktor.io/docs/migration-to-20x.html#serialization-client

Platform Support

  • JVM: Full support with all Java serialization features
  • JavaScript: Browser and Node.js compatibility via platform-specific initialization
  • Native: POSIX platforms support through native serialization
  • WebAssembly: WebAssembly JavaScript target support