0
# Built-in Serializers
1
2
kotlinx.serialization provides a comprehensive set of pre-built serializers for primitive types, collections, arrays, and common Kotlin types. These serializers handle the most common serialization scenarios and serve as building blocks for more complex serialization logic.
3
4
## Capabilities
5
6
### Primitive Type Serializers
7
8
Built-in serializers for all Kotlin primitive types.
9
10
```kotlin { .api }
11
/** Returns serializer for Boolean type */
12
val Boolean.Companion.serializer: KSerializer<Boolean>
13
14
/** Returns serializer for Byte type */
15
val Byte.Companion.serializer: KSerializer<Byte>
16
17
/** Returns serializer for Short type */
18
val Short.Companion.serializer: KSerializer<Short>
19
20
/** Returns serializer for Int type */
21
val Int.Companion.serializer: KSerializer<Int>
22
23
/** Returns serializer for Long type */
24
val Long.Companion.serializer: KSerializer<Long>
25
26
/** Returns serializer for Float type */
27
val Float.Companion.serializer: KSerializer<Float>
28
29
/** Returns serializer for Double type */
30
val Double.Companion.serializer: KSerializer<Double>
31
32
/** Returns serializer for Char type */
33
val Char.Companion.serializer: KSerializer<Char>
34
35
/** Returns serializer for String type */
36
val String.Companion.serializer: KSerializer<String>
37
```
38
39
**Usage Examples:**
40
41
```kotlin
42
import kotlinx.serialization.*
43
import kotlinx.serialization.json.*
44
import kotlinx.serialization.builtins.*
45
46
// Using primitive serializers directly
47
val json = Json
48
49
val intValue = 42
50
val serializedInt = json.encodeToString(Int.serializer(), intValue)
51
val deserializedInt = json.decodeFromString(Int.serializer(), serializedInt)
52
53
val stringValue = "Hello, World!"
54
val serializedString = json.encodeToString(String.serializer(), stringValue)
55
val deserializedString = json.decodeFromString(String.serializer(), serializedString)
56
57
// Primitive serializers are automatically used for @Serializable classes
58
@Serializable
59
data class PrimitiveData(
60
val flag: Boolean, // Uses Boolean.serializer
61
val count: Int, // Uses Int.serializer
62
val name: String, // Uses String.serializer
63
val score: Double // Uses Double.serializer
64
)
65
```
66
67
### Unsigned Type Serializers
68
69
Serializers for Kotlin's unsigned integer types.
70
71
```kotlin { .api }
72
/** Returns serializer for UByte type */
73
val UByte.Companion.serializer: KSerializer<UByte>
74
75
/** Returns serializer for UShort type */
76
val UShort.Companion.serializer: KSerializer<UShort>
77
78
/** Returns serializer for UInt type */
79
val UInt.Companion.serializer: KSerializer<UInt>
80
81
/** Returns serializer for ULong type */
82
val ULong.Companion.serializer: KSerializer<ULong>
83
```
84
85
**Usage Examples:**
86
87
```kotlin
88
@Serializable
89
data class UnsignedData(
90
val smallValue: UByte, // 0..255
91
val mediumValue: UInt, // 0..4,294,967,295
92
val largeValue: ULong // 0..18,446,744,073,709,551,615
93
)
94
95
val data = UnsignedData(255u, 4294967295u, 18446744073709551615u)
96
val json = Json.encodeToString(data)
97
```
98
99
### Array Serializers
100
101
Specialized serializers for Kotlin's primitive array types.
102
103
```kotlin { .api }
104
/** Returns serializer for ByteArray */
105
fun ByteArraySerializer(): KSerializer<ByteArray>
106
107
/** Returns serializer for ShortArray */
108
fun ShortArraySerializer(): KSerializer<ShortArray>
109
110
/** Returns serializer for IntArray */
111
fun IntArraySerializer(): KSerializer<IntArray>
112
113
/** Returns serializer for LongArray */
114
fun LongArraySerializer(): KSerializer<LongArray>
115
116
/** Returns serializer for FloatArray */
117
fun FloatArraySerializer(): KSerializer<FloatArray>
118
119
/** Returns serializer for DoubleArray */
120
fun DoubleArraySerializer(): KSerializer<DoubleArray>
121
122
/** Returns serializer for CharArray */
123
fun CharArraySerializer(): KSerializer<CharArray>
124
125
/** Returns serializer for BooleanArray */
126
fun BooleanArraySerializer(): KSerializer<BooleanArray>
127
128
/** Returns serializer for UByteArray */
129
fun UByteArraySerializer(): KSerializer<UByteArray>
130
131
/** Returns serializer for UShortArray */
132
fun UShortArraySerializer(): KSerializer<UShortArray>
133
134
/** Returns serializer for UIntArray */
135
fun UIntArraySerializer(): KSerializer<UIntArray>
136
137
/** Returns serializer for ULongArray */
138
fun ULongArraySerializer(): KSerializer<ULongArray>
139
```
140
141
**Usage Examples:**
142
143
```kotlin
144
import kotlinx.serialization.builtins.*
145
146
// Serialize primitive arrays
147
val intArray = intArrayOf(1, 2, 3, 4, 5)
148
val serializedArray = Json.encodeToString(IntArraySerializer(), intArray)
149
val deserializedArray = Json.decodeFromString(IntArraySerializer(), serializedArray)
150
151
// In data classes - arrays require explicit serializers
152
@Serializable
153
data class ArrayData(
154
@Serializable(with = ByteArraySerializer::class)
155
val bytes: ByteArray,
156
157
@Serializable(with = IntArraySerializer::class)
158
val numbers: IntArray
159
)
160
```
161
162
### Collection Serializers
163
164
Factory functions for creating serializers for Kotlin collection types.
165
166
```kotlin { .api }
167
/**
168
* Creates a serializer for List<T>.
169
* @param elementSerializer Serializer for list elements
170
* @return KSerializer for List<T>
171
*/
172
fun <T> ListSerializer(elementSerializer: KSerializer<T>): KSerializer<List<T>>
173
174
/**
175
* Creates a serializer for Set<T>.
176
* @param elementSerializer Serializer for set elements
177
* @return KSerializer for Set<T>
178
*/
179
fun <T> SetSerializer(elementSerializer: KSerializer<T>): KSerializer<Set<T>>
180
181
/**
182
* Creates a serializer for Map<K,V>.
183
* @param keySerializer Serializer for map keys
184
* @param valueSerializer Serializer for map values
185
* @return KSerializer for Map<K,V>
186
*/
187
fun <K, V> MapSerializer(
188
keySerializer: KSerializer<K>,
189
valueSerializer: KSerializer<V>
190
): KSerializer<Map<K, V>>
191
192
/**
193
* Creates a serializer for Pair<A,B>.
194
* @param aSerializer Serializer for first element
195
* @param bSerializer Serializer for second element
196
* @return KSerializer for Pair<A,B>
197
*/
198
fun <A, B> PairSerializer(
199
aSerializer: KSerializer<A>,
200
bSerializer: KSerializer<B>
201
): KSerializer<Pair<A, B>>
202
203
/**
204
* Creates a serializer for Triple<A,B,C>.
205
* @param aSerializer Serializer for first element
206
* @param bSerializer Serializer for second element
207
* @param cSerializer Serializer for third element
208
* @return KSerializer for Triple<A,B,C>
209
*/
210
fun <A, B, C> TripleSerializer(
211
aSerializer: KSerializer<A>,
212
bSerializer: KSerializer<B>,
213
cSerializer: KSerializer<C>
214
): KSerializer<Triple<A, B, C>>
215
216
/**
217
* Creates a serializer for Map.Entry<K,V>.
218
* @param keySerializer Serializer for entry keys
219
* @param valueSerializer Serializer for entry values
220
* @return KSerializer for Map.Entry<K,V>
221
*/
222
fun <K, V> MapEntrySerializer(
223
keySerializer: KSerializer<K>,
224
valueSerializer: KSerializer<V>
225
): KSerializer<Map.Entry<K, V>>
226
```
227
228
**Usage Examples:**
229
230
```kotlin
231
import kotlinx.serialization.*
232
import kotlinx.serialization.builtins.*
233
234
// Collection serializers are automatically inferred for @Serializable classes
235
@Serializable
236
data class CollectionData(
237
val names: List<String>, // Uses ListSerializer(String.serializer())
238
val uniqueIds: Set<Int>, // Uses SetSerializer(Int.serializer())
239
val mapping: Map<String, Double> // Uses MapSerializer(String.serializer(), Double.serializer())
240
)
241
242
// Manual collection serialization
243
val listOfInts = listOf(1, 2, 3, 4)
244
val listSerializer = ListSerializer(Int.serializer())
245
val serializedList = Json.encodeToString(listSerializer, listOfInts)
246
247
val mapOfData = mapOf("a" to 1, "b" to 2, "c" to 3)
248
val mapSerializer = MapSerializer(String.serializer(), Int.serializer())
249
val serializedMap = Json.encodeToString(mapSerializer, mapOfData)
250
251
// Nested collections
252
val nestedList = listOf(listOf(1, 2), listOf(3, 4))
253
val nestedSerializer = ListSerializer(ListSerializer(Int.serializer()))
254
val serializedNested = Json.encodeToString(nestedSerializer, nestedList)
255
```
256
257
### Special Type Serializers
258
259
Serializers for special Kotlin types and standard library classes.
260
261
```kotlin { .api }
262
/** Returns serializer for Unit type */
263
val Unit.Companion.serializer: KSerializer<Unit>
264
265
/** Returns serializer for Duration type */
266
val Duration.Companion.serializer: KSerializer<Duration>
267
268
/** Returns serializer for Instant type */
269
val Instant.Companion.serializer: KSerializer<Instant>
270
271
/** Returns serializer for Uuid type */
272
val Uuid.Companion.serializer: KSerializer<Uuid>
273
```
274
275
**Usage Examples:**
276
277
```kotlin
278
import kotlin.time.Duration
279
import kotlinx.datetime.Instant
280
import kotlinx.uuid.Uuid
281
282
@Serializable
283
data class TimedEvent(
284
val id: Uuid,
285
val timestamp: Instant,
286
val duration: Duration,
287
val metadata: Unit = Unit // Often used as a placeholder
288
)
289
290
val event = TimedEvent(
291
id = Uuid.random(),
292
timestamp = Instant.now(),
293
duration = Duration.parse("1h 30m")
294
)
295
296
val json = Json.encodeToString(event)
297
```
298
299
### Nullable Serializers
300
301
Extension property for creating nullable versions of any serializer.
302
303
```kotlin { .api }
304
/**
305
* Returns a nullable serializer for the given non-null serializer.
306
* Handles null values appropriately in the serialization format.
307
*/
308
val <T : Any> KSerializer<T>.nullable: KSerializer<T?>
309
```
310
311
**Usage Examples:**
312
313
```kotlin
314
import kotlinx.serialization.builtins.*
315
316
// Create nullable serializers
317
val nullableStringSerializer = String.serializer().nullable
318
val nullableIntSerializer = Int.serializer().nullable
319
320
// Serialize nullable values
321
val nullableValue: String? = null
322
val serialized = Json.encodeToString(nullableStringSerializer, nullableValue)
323
// Result: "null"
324
325
val nonNullValue: String? = "Hello"
326
val serialized2 = Json.encodeToString(nullableStringSerializer, nonNullValue)
327
// Result: "\"Hello\""
328
329
// In data classes - nullable properties are handled automatically
330
@Serializable
331
data class OptionalData(
332
val name: String,
333
val nickname: String? = null, // Automatically uses String.serializer().nullable
334
val age: Int? = null // Automatically uses Int.serializer().nullable
335
)
336
```
337
338
### Utility Serializers
339
340
Additional specialized serializers for specific use cases available in the JVM-specific extensions.
341
342
```kotlin { .api }
343
/**
344
* Serializer that represents Long values as strings.
345
* Useful for JavaScript compatibility where large numbers lose precision.
346
*/
347
object LongAsStringSerializer : KSerializer<Long>
348
349
/**
350
* Serializer for Instant that handles nanosecond precision.
351
* Provides more precise timestamp serialization than the default.
352
*/
353
object InstantComponentSerializer : KSerializer<Instant>
354
```
355
356
## Integration Patterns
357
358
### Custom Serializer Composition
359
360
Built-in serializers can be composed to create more complex serializers:
361
362
```kotlin
363
import kotlinx.serialization.*
364
import kotlinx.serialization.builtins.*
365
import kotlinx.serialization.encoding.*
366
import kotlinx.serialization.descriptors.*
367
368
// Custom serializer using built-in serializers as components
369
object CoordinateSerializer : KSerializer<Coordinate> {
370
private val doubleSerializer = Double.serializer()
371
372
override val descriptor = buildClassSerialDescriptor("Coordinate") {
373
element("lat", doubleSerializer.descriptor)
374
element("lng", doubleSerializer.descriptor)
375
}
376
377
override fun serialize(encoder: Encoder, value: Coordinate) {
378
encoder.encodeStructure(descriptor) {
379
encodeSerializableElement(descriptor, 0, doubleSerializer, value.lat)
380
encodeSerializableElement(descriptor, 1, doubleSerializer, value.lng)
381
}
382
}
383
384
override fun deserialize(decoder: Decoder): Coordinate {
385
return decoder.decodeStructure(descriptor) {
386
var lat = 0.0
387
var lng = 0.0
388
389
while (true) {
390
when (val index = decodeElementIndex(descriptor)) {
391
0 -> lat = decodeSerializableElement(descriptor, index, doubleSerializer)
392
1 -> lng = decodeSerializableElement(descriptor, index, doubleSerializer)
393
CompositeDecoder.DECODE_DONE -> break
394
else -> error("Unexpected index: $index")
395
}
396
}
397
398
Coordinate(lat, lng)
399
}
400
}
401
}
402
```
403
404
### Format-Specific Considerations
405
406
Some built-in serializers may behave differently depending on the format:
407
408
```kotlin
409
// JSON handles numbers naturally
410
val jsonResult = Json.encodeToString(Long.serializer(), 123456789012345L)
411
// Result: 123456789012345
412
413
// For JavaScript compatibility, use LongAsStringSerializer
414
val jsCompatibleResult = Json.encodeToString(LongAsStringSerializer, 123456789012345L)
415
// Result: "123456789012345"
416
417
// Binary formats handle all numeric types efficiently
418
val protobufResult = ProtoBuf.encodeToByteArray(Long.serializer(), 123456789012345L)
419
```
420
421
## Error Handling
422
423
Common errors when working with built-in serializers:
424
425
- **SerializationException**: Type mismatches or invalid data during deserialization
426
- **IllegalArgumentException**: Invalid configuration or null values for non-nullable serializers
427
- **NumberFormatException**: Invalid numeric strings when deserializing number types
428
- **ClassCastException**: Incorrect serializer usage for collection types