Kotlinx Serialization support for Ktor HTTP Client, providing JSON serialization and deserialization capabilities for data classes marked with @Serializable annotation.
npx @tessl/cli install tessl/maven-io-ktor--ktor-client-serialization@3.2.0Ktor 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.
build.gradle.kts:
implementation("io.ktor:ktor-client-serialization:3.2.0")import io.ktor.client.plugins.kotlinx.serializer.KotlinxSerializer
import kotlinx.serialization.json.Jsonimport 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()
// }
// }The package is built around the following key components:
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 PersonSerializes 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): OutgoingContentDeserializes 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): AnyProvides a default Json configuration optimized for Ktor client usage.
/**
* Default Json configuration for KotlinxSerializer.
*/
val DefaultJson: JsonThe default configuration includes:
isLenient = false - Strict JSON parsingignoreUnknownKeys = false - Fail on unknown propertiesallowSpecialFloatingPointValues = true - Support for NaN and InfinityuseArrayPolymorphism = false - Use object-based polymorphic serializationEach 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 SerializerInitializerThe initialization ensures that KotlinxSerializer is automatically available in the platform-specific serializer stores/registries without manual registration.
/**
* 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 SerializersModuleThe serializer automatically handles:
The serializer may throw exceptions in the following cases:
"Serializing collections of different element types is not yet supported. Selected serializers: [list of serializer names]"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