0
# Core Serialization
1
2
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.
3
4
## Capabilities
5
6
### Core Interfaces
7
8
The foundation interfaces that define serialization behavior for any type.
9
10
```kotlin { .api }
11
/**
12
* The main serialization interface combining both serialization and deserialization strategies.
13
* Every serializable type has an associated KSerializer that handles conversion to/from formats.
14
*/
15
interface KSerializer<T> : SerializationStrategy<T>, DeserializationStrategy<T> {
16
override val descriptor: SerialDescriptor
17
}
18
19
/**
20
* Defines the serialization process for converting objects to their serial form.
21
* Contains the structural description and serialization logic.
22
*/
23
interface SerializationStrategy<in T> {
24
val descriptor: SerialDescriptor
25
fun serialize(encoder: Encoder, value: T)
26
}
27
28
/**
29
* Defines the deserialization process for converting serial form back to objects.
30
* Contains the structural description and deserialization logic.
31
*/
32
interface DeserializationStrategy<out T> {
33
val descriptor: SerialDescriptor
34
fun deserialize(decoder: Decoder): T
35
}
36
```
37
38
**Usage Examples:**
39
40
```kotlin
41
import kotlinx.serialization.*
42
import kotlinx.serialization.json.*
43
44
@Serializable
45
data class User(val name: String, val age: Int)
46
47
// Get the generated serializer
48
val userSerializer: KSerializer<User> = User.serializer()
49
50
// Use it directly with format
51
val json = Json.encodeToString(userSerializer, User("Alice", 25))
52
val user = Json.decodeFromString(userSerializer, json)
53
```
54
55
### Serializer Lookup Functions
56
57
Functions for obtaining serializers at runtime, including type-safe and reflection-based approaches.
58
59
```kotlin { .api }
60
/**
61
* Retrieves a serializer for the given reified type T.
62
* This is the primary way to get serializers for known types at compile time.
63
*/
64
inline fun <reified T> serializer(): KSerializer<T>
65
66
/**
67
* Creates a serializer for the given KType.
68
* Useful for runtime serializer resolution when type information is dynamic.
69
* @param type The KType to create a serializer for
70
* @return KSerializer for the specified type
71
* @throws SerializationException if serializer cannot be created
72
*/
73
fun serializer(type: KType): KSerializer<Any?>
74
75
/**
76
* Creates a serializer for the given KType, returning null if not possible.
77
* Safe variant that doesn't throw exceptions on failure.
78
* @param type The KType to create a serializer for
79
* @return KSerializer for the type, or null if unavailable
80
*/
81
fun serializerOrNull(type: KType): KSerializer<Any?>?
82
83
/**
84
* JVM-specific: Creates a serializer for the given Java Type.
85
* Provides Java interoperability for runtime serializer resolution.
86
* @param type The Java Type to create a serializer for
87
* @return KSerializer for the specified Java type (non-nullable)
88
* @throws SerializationException if serializer cannot be created
89
*/
90
fun serializer(type: java.lang.reflect.Type): KSerializer<Any>
91
92
/**
93
* JVM-specific: Creates a serializer for the given Java Type, returning null if not possible.
94
* Safe variant for Java Type serializer resolution.
95
* @param type The Java Type to create a serializer for
96
* @return KSerializer for the type, or null if unavailable (non-nullable)
97
*/
98
fun serializerOrNull(type: java.lang.reflect.Type): KSerializer<Any>?
99
```
100
101
**Usage Examples:**
102
103
```kotlin
104
import kotlinx.serialization.*
105
import kotlin.reflect.typeOf
106
107
// Compile-time serializer lookup (preferred)
108
val stringSerializer = serializer<String>()
109
val listSerializer = serializer<List<Int>>()
110
111
// Runtime serializer lookup
112
val userType = typeOf<User>()
113
val userSerializer = serializer(userType) as KSerializer<User>
114
115
// Safe runtime lookup
116
val maybeSerializer = serializerOrNull(typeOf<SomeClass>())
117
if (maybeSerializer != null) {
118
// Use serializer
119
}
120
121
// JVM-specific: Java Type serialization
122
import java.lang.reflect.Type
123
124
val javaType: Type = User::class.java
125
val javaSerializer = serializer(javaType) as KSerializer<User>
126
127
// Safe Java Type lookup
128
val maybejavaSerializer = serializerOrNull(javaType)
129
```
130
131
### Format Interfaces
132
133
Base interfaces that serialization formats implement to provide encoding/decoding capabilities.
134
135
```kotlin { .api }
136
/**
137
* Base interface for all serialization formats.
138
* Provides access to the serializers module for custom serializer resolution.
139
*/
140
interface SerialFormat {
141
val serializersModule: SerializersModule
142
}
143
144
/**
145
* Serialization format that converts objects to/from strings.
146
* Implemented by text-based formats like JSON, XML, YAML.
147
*/
148
interface StringFormat : SerialFormat {
149
fun <T> encodeToString(serializer: SerializationStrategy<T>, value: T): String
150
fun <T> decodeFromString(deserializer: DeserializationStrategy<T>, string: String): T
151
}
152
153
/**
154
* Serialization format that converts objects to/from byte arrays.
155
* Implemented by binary formats like ProtoBuf, CBOR, MessagePack.
156
*/
157
interface BinaryFormat : SerialFormat {
158
fun <T> encodeToByteArray(serializer: SerializationStrategy<T>, value: T): ByteArray
159
fun <T> decodeFromByteArray(deserializer: DeserializationStrategy<T>, bytes: ByteArray): T
160
}
161
```
162
163
### Format Extension Functions
164
165
Convenient extension functions that provide reified type parameter support for format operations.
166
167
```kotlin { .api }
168
/**
169
* Encodes the given value to string using reified type parameter.
170
* @param value The value to encode
171
* @return Encoded string representation
172
*/
173
inline fun <reified T> StringFormat.encodeToString(value: T): String
174
175
/**
176
* Decodes a string to the specified type using reified type parameter.
177
* @param string The string to decode
178
* @return Decoded value of type T
179
*/
180
inline fun <reified T> StringFormat.decodeFromString(string: String): T
181
182
/**
183
* Encodes the given value to byte array using reified type parameter.
184
* @param value The value to encode
185
* @return Encoded byte array
186
*/
187
inline fun <reified T> BinaryFormat.encodeToByteArray(value: T): ByteArray
188
189
/**
190
* Decodes a byte array to the specified type using reified type parameter.
191
* @param bytes The byte array to decode
192
* @return Decoded value of type T
193
*/
194
inline fun <reified T> BinaryFormat.decodeFromByteArray(bytes: ByteArray): T
195
196
/**
197
* Encodes the given value to hex string representation using BinaryFormat.
198
* @param value The value to encode
199
* @return Hex string representation of encoded bytes
200
*/
201
inline fun <reified T> BinaryFormat.encodeToHexString(value: T): String
202
203
/**
204
* Decodes a hex string to the specified type using BinaryFormat.
205
* @param hex The hex string to decode
206
* @return Decoded value of type T
207
*/
208
inline fun <reified T> BinaryFormat.decodeFromHexString(hex: String): T
209
```
210
211
**Usage Examples:**
212
213
```kotlin
214
import kotlinx.serialization.*
215
import kotlinx.serialization.json.*
216
217
val json = Json
218
219
@Serializable
220
data class Person(val name: String, val age: Int)
221
222
val person = Person("Bob", 30)
223
224
// Using extension functions (preferred)
225
val jsonString = json.encodeToString(person)
226
val decoded = json.decodeFromString<Person>(jsonString)
227
228
// Using format interface directly
229
val jsonString2 = json.encodeToString(Person.serializer(), person)
230
val decoded2 = json.decodeFromString(Person.serializer(), jsonString2)
231
```
232
233
### Polymorphic Serializers
234
235
Specialized serializers for handling polymorphic types and runtime type resolution.
236
237
```kotlin { .api }
238
/**
239
* Provides multiplatform polymorphic serialization for open classes, interfaces, and abstract classes.
240
* Used when the actual runtime type needs to be preserved during serialization.
241
*/
242
class PolymorphicSerializer<T : Any>(val baseClass: KClass<T>) : AbstractPolymorphicSerializer<T>()
243
244
/**
245
* Provides polymorphic serialization specifically for sealed classes.
246
* Optimized for sealed class hierarchies with compile-time known subclasses.
247
*/
248
class SealedClassSerializer<T : Any>(
249
serialName: String,
250
val baseClass: KClass<T>,
251
subclassSerializers: Array<KSerializer<out T>>
252
) : AbstractPolymorphicSerializer<T>()
253
254
/**
255
* Provides runtime serializer retrieval from SerializersModule instead of compile-time resolution.
256
* Used with @Contextual annotation for types that need runtime serializer lookup.
257
*/
258
class ContextualSerializer<T : Any>(
259
val serializerClass: KClass<T>,
260
val fallbackSerializer: KSerializer<T>? = null
261
) : KSerializer<T>
262
```
263
264
**Usage Examples:**
265
266
```kotlin
267
import kotlinx.serialization.*
268
import kotlinx.serialization.json.*
269
import kotlinx.serialization.modules.*
270
271
// Sealed class serialization
272
@Serializable
273
sealed class Result {
274
@Serializable
275
data class Success(val data: String) : Result()
276
277
@Serializable
278
data class Error(val message: String) : Result()
279
}
280
281
// Polymorphic interface serialization
282
@Serializable
283
@JsonClassDiscriminator("type")
284
sealed interface Animal {
285
@Serializable
286
@SerialName("dog")
287
data class Dog(val breed: String) : Animal
288
289
@Serializable
290
@SerialName("cat")
291
data class Cat(val indoor: Boolean) : Animal
292
}
293
294
// Contextual serialization for external types
295
val module = SerializersModule {
296
contextual(UUID::class, UUIDSerializer)
297
}
298
299
val json = Json { serializersModule = module }
300
301
@Serializable
302
data class Document(
303
@Contextual val id: UUID,
304
val title: String
305
)
306
```
307
308
## Exception Classes
309
310
```kotlin { .api }
311
/**
312
* Generic exception for serialization and deserialization problems.
313
* Base class for all serialization-related exceptions.
314
*/
315
open class SerializationException(
316
message: String? = null,
317
cause: Throwable? = null
318
) : IllegalArgumentException(message, cause)
319
320
/**
321
* Thrown when a KSerializer didn't receive a non-optional property during deserialization.
322
* Indicates missing required fields in the input data.
323
*/
324
class MissingFieldException(
325
val fieldName: String,
326
val serialName: String = fieldName
327
) : SerializationException(
328
"Field '$fieldName' is required for type with serial name '$serialName', but it was missing"
329
)
330
```
331
332
## Error Handling
333
334
Common serialization errors and their typical causes:
335
336
- **SerializationException**: General serialization failures, often due to format incompatibilities
337
- **MissingFieldException**: Required fields missing from input data
338
- **IllegalArgumentException**: Invalid serializer configurations or malformed data
339
- **ClassCastException**: Type mismatches during polymorphic deserialization