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.00
# Ktor Client Serialization
1
2
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.
3
4
**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.
5
6
## Package Information
7
8
- **Package Name**: ktor-client-serialization
9
- **Package Type**: maven
10
- **Language**: Kotlin (multiplatform)
11
- **Installation**: Add to `build.gradle.kts`:
12
```kotlin
13
implementation("io.ktor:ktor-client-serialization:3.2.0")
14
```
15
16
## Core Imports
17
18
```kotlin
19
import io.ktor.client.plugins.kotlinx.serializer.KotlinxSerializer
20
import kotlinx.serialization.json.Json
21
```
22
23
## Basic Usage
24
25
```kotlin
26
import io.ktor.client.plugins.kotlinx.serializer.KotlinxSerializer
27
import kotlinx.serialization.Serializable
28
import kotlinx.serialization.json.Json
29
30
// Define a serializable data class
31
@Serializable
32
data class User(val name: String, val age: Int)
33
34
// Create serializer with default configuration
35
val serializer = KotlinxSerializer()
36
37
// Or with custom Json configuration
38
val customJson = Json {
39
ignoreUnknownKeys = true
40
isLenient = true
41
}
42
val customSerializer = KotlinxSerializer(customJson)
43
44
// Use with legacy JSON plugin (deprecated)
45
// HttpClient {
46
// install(JsonFeature) {
47
// serializer = KotlinxSerializer()
48
// }
49
// }
50
```
51
52
## Architecture
53
54
The package is built around the following key components:
55
56
- **KotlinxSerializer**: Main serializer class implementing the JsonSerializer interface
57
- **Json Configuration**: Configurable JSON processing with kotlinx.serialization
58
- **Multiplatform Support**: Platform-specific initialization for JVM, JS, Native, and WebAssembly
59
- **Type Detection**: Automatic serialization strategy selection based on data types
60
- **Legacy Integration**: Compatibility with the deprecated JSON plugin system
61
62
## Capabilities
63
64
### JSON Serialization
65
66
The KotlinxSerializer class provides JSON serialization and deserialization capabilities for Kotlin data classes.
67
68
```kotlin { .api }
69
/**
70
* A JsonSerializer implemented for kotlinx Serializable classes.
71
*
72
* @deprecated Please use ContentNegotiation plugin and its converters
73
*/
74
@Deprecated(
75
"Please use ContentNegotiation plugin and its converters: https://ktor.io/docs/migration-to-20x.html#serialization-client",
76
level = DeprecationLevel.ERROR
77
)
78
class KotlinxSerializer(
79
private val json: Json = DefaultJson
80
) : JsonSerializer {
81
82
/**
83
* Convert data object to OutgoingContent with specified content type.
84
*/
85
fun write(data: Any, contentType: ContentType): OutgoingContent
86
87
/**
88
* Convert data object to OutgoingContent with default JSON content type.
89
*/
90
fun write(data: Any): OutgoingContent
91
92
/**
93
* Read content from response using information specified in type.
94
*/
95
fun read(type: TypeInfo, body: Input): Any
96
97
98
companion object {
99
/**
100
* Default Json configuration for KotlinxSerializer.
101
*/
102
val DefaultJson: Json
103
}
104
}
105
```
106
107
**Usage Examples:**
108
109
```kotlin
110
import io.ktor.client.plugins.kotlinx.serializer.KotlinxSerializer
111
import io.ktor.http.ContentType
112
import io.ktor.util.reflect.typeInfo
113
import io.ktor.utils.io.core.ByteReadPacket
114
import kotlinx.serialization.Serializable
115
116
@Serializable
117
data class Person(val name: String, val email: String)
118
119
val serializer = KotlinxSerializer()
120
121
// Serialize data to OutgoingContent
122
val person = Person("Alice", "alice@example.com")
123
val content = serializer.write(person, ContentType.Application.Json)
124
125
// Deserialize from Input (using ktor Input type)
126
val jsonBytes = """{"name":"Bob","email":"bob@example.com"}""".toByteArray()
127
val jsonInput = ByteReadPacket(jsonBytes)
128
val deserializedPerson = serializer.read(typeInfo<Person>(), jsonInput) as Person
129
```
130
131
### Write Operations
132
133
Serializes Kotlin objects to JSON format as OutgoingContent.
134
135
```kotlin { .api }
136
/**
137
* Convert data object to OutgoingContent with specified content type.
138
* @param data The object to serialize
139
* @param contentType The content type for the output
140
* @return OutgoingContent containing the serialized JSON
141
*/
142
fun write(data: Any, contentType: ContentType): OutgoingContent
143
```
144
145
### Read Operations
146
147
Deserializes JSON content to Kotlin objects using type information.
148
149
```kotlin { .api }
150
/**
151
* Read content from response using information specified in type.
152
* @param type TypeInfo containing the target type information
153
* @param body Input stream containing JSON data
154
* @return Deserialized object of the specified type
155
*/
156
fun read(type: TypeInfo, body: Input): Any
157
```
158
159
### Default Configuration
160
161
Provides a default Json configuration optimized for Ktor client usage.
162
163
```kotlin { .api }
164
/**
165
* Default Json configuration for KotlinxSerializer.
166
*/
167
val DefaultJson: Json
168
```
169
170
The default configuration includes:
171
- `isLenient = false` - Strict JSON parsing
172
- `ignoreUnknownKeys = false` - Fail on unknown properties
173
- `allowSpecialFloatingPointValues = true` - Support for NaN and Infinity
174
- `useArrayPolymorphism = false` - Use object-based polymorphic serialization
175
176
### Platform Initialization
177
178
Each platform provides automatic initialization for the serializer registry.
179
180
```kotlin { .api }
181
/**
182
* Platform-specific eager initialization object that registers KotlinxSerializer.
183
* Available on JS, POSIX (Native), and WebAssembly platforms.
184
*/
185
@OptIn(ExperimentalStdlibApi::class)
186
@InternalAPI
187
@EagerInitialization
188
object SerializerInitializer
189
```
190
191
The initialization ensures that KotlinxSerializer is automatically available in the platform-specific serializer stores/registries without manual registration.
192
193
## Types
194
195
```kotlin { .api }
196
/**
197
* Base interface for JSON serializers in Ktor client.
198
*/
199
@Deprecated(
200
"Please use ContentNegotiation plugin and its converters",
201
level = DeprecationLevel.ERROR
202
)
203
interface JsonSerializer {
204
fun write(data: Any, contentType: ContentType): OutgoingContent
205
fun write(data: Any): OutgoingContent
206
fun read(type: TypeInfo, body: Input): Any
207
}
208
209
/**
210
* Content type for HTTP requests and responses.
211
*/
212
class ContentType {
213
companion object {
214
object Application {
215
val Json: ContentType
216
}
217
}
218
}
219
220
/**
221
* Type information for deserialization.
222
*/
223
class TypeInfo
224
225
/**
226
* Input interface for reading data from ktor.utils.io.core.
227
*/
228
interface Input
229
230
/**
231
* Content that can be sent in HTTP requests.
232
*/
233
interface OutgoingContent
234
235
/**
236
* Kotlinx Serialization Json configuration.
237
* From kotlinx.serialization.json package.
238
*/
239
class Json {
240
val isLenient: Boolean
241
val ignoreUnknownKeys: Boolean
242
val allowSpecialFloatingPointValues: Boolean
243
val useArrayPolymorphism: Boolean
244
val serializersModule: SerializersModule
245
246
companion object {
247
operator fun invoke(builderAction: JsonBuilder.() -> Unit): Json
248
}
249
}
250
251
/**
252
* Kotlinx Serialization serializers module.
253
*/
254
class SerializersModule
255
```
256
257
## Supported Types
258
259
The serializer automatically handles:
260
261
- **@Serializable data classes**: Primary use case with full type safety
262
- **Collections**: List, Set, Array with element type detection
263
- **Maps**: Map<K,V> with serializable keys and values
264
- **Primitive types**: String, Int, Long, Float, Double, Boolean
265
- **JsonElement types**: Direct kotlinx.serialization JSON elements
266
- **Nullable types**: Optional values with proper null handling
267
- **Polymorphic types**: With proper serialization configuration
268
269
## Error Handling
270
271
The serializer may throw exceptions in the following cases:
272
273
- **SerializationException**: When serialization/deserialization fails due to incompatible data structures or missing @Serializable annotations
274
- **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]"`
275
- **JsonDecodingException**: When JSON parsing fails due to malformed JSON or invalid syntax
276
- **ClassCastException**: When type information doesn't match actual data during deserialization
277
- **Error**: For mixed collection element types that cannot be unified under a single serializer
278
279
## Migration Guide
280
281
This package is deprecated. Migrate to ContentNegotiation:
282
283
**Old approach (deprecated):**
284
```kotlin
285
HttpClient {
286
install(JsonFeature) {
287
serializer = KotlinxSerializer()
288
}
289
}
290
```
291
292
**New approach (recommended):**
293
```kotlin
294
HttpClient {
295
install(ContentNegotiation) {
296
json(Json {
297
ignoreUnknownKeys = true
298
})
299
}
300
}
301
```
302
303
For detailed migration instructions, see: https://ktor.io/docs/migration-to-20x.html#serialization-client
304
305
## Platform Support
306
307
- **JVM**: Full support with all Java serialization features
308
- **JavaScript**: Browser and Node.js compatibility via platform-specific initialization
309
- **Native**: POSIX platforms support through native serialization
310
- **WebAssembly**: WebAssembly JavaScript target support