0
# Built-in Serializers
1
2
kotlinx-serialization-core provides a comprehensive collection of built-in serializers for Kotlin standard library types. These serializers handle primitives, collections, arrays, and other common types without requiring custom implementation.
3
4
## Primitive Serializers
5
6
### Basic Types
7
8
```kotlin { .api }
9
fun Boolean.Companion.serializer(): KSerializer<Boolean>
10
fun Byte.Companion.serializer(): KSerializer<Byte>
11
fun Short.Companion.serializer(): KSerializer<Short>
12
fun Int.Companion.serializer(): KSerializer<Int>
13
fun Long.Companion.serializer(): KSerializer<Long>
14
fun Float.Companion.serializer(): KSerializer<Float>
15
fun Double.Companion.serializer(): KSerializer<Double>
16
fun Char.Companion.serializer(): KSerializer<Char>
17
fun String.Companion.serializer(): KSerializer<String>
18
fun Unit.Companion.serializer(): KSerializer<Unit>
19
```
20
21
**Usage:**
22
```kotlin
23
val intSerializer = Int.serializer()
24
val stringSerializer = String.serializer()
25
val booleanSerializer = Boolean.serializer()
26
```
27
28
### Unsigned Types
29
30
```kotlin { .api }
31
fun UByte.Companion.serializer(): KSerializer<UByte>
32
fun UShort.Companion.serializer(): KSerializer<UShort>
33
fun UInt.Companion.serializer(): KSerializer<UInt>
34
fun ULong.Companion.serializer(): KSerializer<ULong>
35
```
36
37
## Nullable Serializers
38
39
### Nullable Extension
40
41
```kotlin { .api }
42
val <T> KSerializer<T>.nullable: KSerializer<T?>
43
```
44
45
**Usage:**
46
```kotlin
47
val nullableStringSerializer = String.serializer().nullable
48
val nullableIntSerializer = Int.serializer().nullable
49
50
// For custom types
51
val nullableUserSerializer = User.serializer().nullable
52
```
53
54
## Collection Serializers
55
56
### Lists and Sets
57
58
```kotlin { .api }
59
fun <T> ListSerializer(elementSerializer: KSerializer<T>): KSerializer<List<T>>
60
fun <T> SetSerializer(elementSerializer: KSerializer<T>): KSerializer<Set<T>>
61
fun <T> LinkedHashSetSerializer(elementSerializer: KSerializer<T>): KSerializer<LinkedHashSet<T>>
62
fun <T> HashSetSerializer(elementSerializer: KSerializer<T>): KSerializer<HashSet<T>>
63
```
64
65
**Usage:**
66
```kotlin
67
val stringListSerializer = ListSerializer(String.serializer())
68
val intSetSerializer = SetSerializer(Int.serializer())
69
val userListSerializer = ListSerializer(User.serializer())
70
71
// For nested collections
72
val listOfListsSerializer = ListSerializer(ListSerializer(String.serializer()))
73
```
74
75
### Maps
76
77
```kotlin { .api }
78
fun <K, V> MapSerializer(
79
keySerializer: KSerializer<K>,
80
valueSerializer: KSerializer<V>
81
): KSerializer<Map<K, V>>
82
83
fun <K, V> LinkedHashMapSerializer(
84
keySerializer: KSerializer<K>,
85
valueSerializer: KSerializer<V>
86
): KSerializer<LinkedHashMap<K, V>>
87
88
fun <K, V> HashMapSerializer(
89
keySerializer: KSerializer<K>,
90
valueSerializer: KSerializer<V>
91
): KSerializer<HashMap<K, V>>
92
```
93
94
**Usage:**
95
```kotlin
96
val stringIntMapSerializer = MapSerializer(String.serializer(), Int.serializer())
97
val userDataMapSerializer = MapSerializer(String.serializer(), User.serializer())
98
99
// Complex nested maps
100
val nestedMapSerializer = MapSerializer(
101
String.serializer(),
102
MapSerializer(String.serializer(), Int.serializer())
103
)
104
```
105
106
## Array Serializers
107
108
### Generic Arrays
109
110
```kotlin { .api }
111
@ExperimentalSerializationApi
112
inline fun <reified T : Any, reified E : T?> ArraySerializer(
113
elementSerializer: KSerializer<E>
114
): KSerializer<Array<E>>
115
116
@ExperimentalSerializationApi
117
fun <T : Any, E : T?> ArraySerializer(
118
kClass: KClass<T>,
119
elementSerializer: KSerializer<E>
120
): KSerializer<Array<E>>
121
```
122
123
**Usage:**
124
```kotlin
125
@OptIn(ExperimentalSerializationApi::class)
126
val stringArraySerializer = ArraySerializer(String.serializer())
127
val userArraySerializer = ArraySerializer(User::class, User.serializer())
128
```
129
130
### Primitive Arrays
131
132
```kotlin { .api }
133
fun ByteArraySerializer(): KSerializer<ByteArray>
134
fun ShortArraySerializer(): KSerializer<ShortArray>
135
fun IntArraySerializer(): KSerializer<IntArray>
136
fun LongArraySerializer(): KSerializer<LongArray>
137
fun FloatArraySerializer(): KSerializer<FloatArray>
138
fun DoubleArraySerializer(): KSerializer<DoubleArray>
139
fun CharArraySerializer(): KSerializer<CharArray>
140
fun BooleanArraySerializer(): KSerializer<BooleanArray>
141
```
142
143
### Unsigned Primitive Arrays
144
145
```kotlin { .api }
146
@ExperimentalSerializationApi
147
@ExperimentalUnsignedTypes
148
fun UByteArraySerializer(): KSerializer<UByteArray>
149
150
@ExperimentalSerializationApi
151
@ExperimentalUnsignedTypes
152
fun UShortArraySerializer(): KSerializer<UShortArray>
153
154
@ExperimentalSerializationApi
155
@ExperimentalUnsignedTypes
156
fun UIntArraySerializer(): KSerializer<UIntArray>
157
158
@ExperimentalSerializationApi
159
@ExperimentalUnsignedTypes
160
fun ULongArraySerializer(): KSerializer<ULongArray>
161
```
162
163
**Usage:**
164
```kotlin
165
val byteArraySerializer = ByteArraySerializer()
166
val intArraySerializer = IntArraySerializer()
167
168
@OptIn(ExperimentalSerializationApi::class, ExperimentalUnsignedTypes::class)
169
val uintArraySerializer = UIntArraySerializer()
170
```
171
172
## Tuple Serializers
173
174
### Pair and Triple
175
176
```kotlin { .api }
177
fun <A, B> PairSerializer(
178
aSerializer: KSerializer<A>,
179
bSerializer: KSerializer<B>
180
): KSerializer<Pair<A, B>>
181
182
fun <A, B, C> TripleSerializer(
183
aSerializer: KSerializer<A>,
184
bSerializer: KSerializer<B>,
185
cSerializer: KSerializer<C>
186
): KSerializer<Triple<A, B, C>>
187
```
188
189
**Usage:**
190
```kotlin
191
val stringIntPairSerializer = PairSerializer(String.serializer(), Int.serializer())
192
val userDataTripleSerializer = TripleSerializer(
193
String.serializer(),
194
Int.serializer(),
195
User.serializer()
196
)
197
```
198
199
## Map Entry Serializers
200
201
```kotlin { .api }
202
fun <K, V> MapEntrySerializer(
203
keySerializer: KSerializer<K>,
204
valueSerializer: KSerializer<V>
205
): KSerializer<Map.Entry<K, V>>
206
```
207
208
**Usage:**
209
```kotlin
210
val stringIntEntrySerializer = MapEntrySerializer(String.serializer(), Int.serializer())
211
212
// Useful for serializing individual map entries
213
val entry: Map.Entry<String, Int> = mapOf("key" to 42).entries.first()
214
```
215
216
## Time and UUID Serializers
217
218
### Duration Serializer
219
220
```kotlin { .api }
221
fun Duration.Companion.serializer(): KSerializer<Duration>
222
```
223
224
### Instant Serializer
225
226
```kotlin { .api }
227
@ExperimentalTime
228
fun Instant.Companion.serializer(): KSerializer<Instant>
229
```
230
231
### UUID Serializer
232
233
```kotlin { .api }
234
@ExperimentalUuidApi
235
fun Uuid.Companion.serializer(): KSerializer<Uuid>
236
```
237
238
**Usage:**
239
```kotlin
240
val durationSerializer = Duration.serializer()
241
242
@OptIn(ExperimentalTime::class)
243
val instantSerializer = Instant.serializer()
244
245
@OptIn(ExperimentalUuidApi::class)
246
val uuidSerializer = Uuid.serializer()
247
```
248
249
## Special Serializers
250
251
### Nothing Serializer
252
253
```kotlin { .api }
254
@ExperimentalSerializationApi
255
fun NothingSerializer(): KSerializer<Nothing>
256
```
257
258
## Usage Examples
259
260
### Basic Serializer Usage
261
262
```kotlin
263
// Simple types
264
val stringSerializer = String.serializer()
265
val intSerializer = Int.serializer()
266
267
// Collections
268
val stringList = listOf("apple", "banana", "cherry")
269
val stringListSerializer = ListSerializer(String.serializer())
270
271
val userMap = mapOf("john" to User("John", 30), "jane" to User("Jane", 25))
272
val userMapSerializer = MapSerializer(String.serializer(), User.serializer())
273
```
274
275
### Complex Nested Structures
276
277
```kotlin
278
// List of maps
279
val listOfMapsSerializer = ListSerializer(
280
MapSerializer(String.serializer(), Int.serializer())
281
)
282
283
// Map of lists
284
val mapOfListsSerializer = MapSerializer(
285
String.serializer(),
286
ListSerializer(User.serializer())
287
)
288
289
// Nested collections with custom types
290
@Serializable
291
data class Department(val name: String, val employees: List<User>)
292
293
val departmentListSerializer = ListSerializer(Department.serializer())
294
```
295
296
### Nullable Collections
297
298
```kotlin
299
// Nullable collection
300
val nullableListSerializer = ListSerializer(String.serializer()).nullable
301
302
// Collection of nullable elements
303
val listOfNullablesSerializer = ListSerializer(String.serializer().nullable)
304
305
// Both nullable collection and nullable elements
306
val nullableListOfNullablesSerializer = ListSerializer(String.serializer().nullable).nullable
307
```
308
309
### Arrays and Primitive Arrays
310
311
```kotlin
312
// Generic arrays
313
val stringArraySerializer = ArraySerializer(String.serializer())
314
val userArraySerializer = ArraySerializer(User::class, User.serializer())
315
316
// Primitive arrays (more efficient)
317
val intArraySerializer = IntArraySerializer()
318
val byteArraySerializer = ByteArraySerializer()
319
320
// Example usage
321
val numbers = intArrayOf(1, 2, 3, 4, 5)
322
val bytes = byteArrayOf(0x01, 0x02, 0x03)
323
```
324
325
### Working with Tuples
326
327
```kotlin
328
// Simple pair
329
val coordinateSerializer = PairSerializer(Double.serializer(), Double.serializer())
330
val coordinate: Pair<Double, Double> = 10.5 to 20.3
331
332
// Complex triple with mixed types
333
val recordSerializer = TripleSerializer(
334
String.serializer(), // ID
335
LocalDateTime.serializer(), // Timestamp (requires contextual registration)
336
User.serializer() // User data
337
)
338
```
339
340
### Serializer Composition Patterns
341
342
```kotlin
343
// Building complex serializers from simpler ones
344
class UserRepository {
345
// Serializer for user lookup cache
346
val userCacheSerializer = MapSerializer(
347
String.serializer(), // User ID
348
PairSerializer( // Cached data
349
User.serializer(), // User object
350
Long.serializer() // Cache timestamp
351
).nullable // May be null if not cached
352
)
353
354
// Serializer for operation results
355
val operationResultSerializer = PairSerializer(
356
Boolean.serializer(), // Success flag
357
ListSerializer( // Error messages
358
String.serializer()
359
)
360
)
361
}
362
```
363
364
### Performance Considerations
365
366
```kotlin
367
// Prefer primitive array serializers for performance
368
val efficientByteArraySerializer = ByteArraySerializer() // Fast
369
val genericByteArraySerializer = ArraySerializer(Byte.serializer()) // Slower
370
371
// Cache serializers when used frequently
372
object SerializerCache {
373
val stringListSerializer = ListSerializer(String.serializer())
374
val userMapSerializer = MapSerializer(String.serializer(), User.serializer())
375
376
// Reuse these instances instead of creating new ones each time
377
}
378
```
379
380
## Integration with Custom Types
381
382
```kotlin
383
@Serializable
384
data class CustomCollection<T>(
385
val items: List<T>,
386
val metadata: Map<String, String>
387
) {
388
companion object {
389
fun <T> serializer(elementSerializer: KSerializer<T>): KSerializer<CustomCollection<T>> {
390
return CustomCollection.serializer(elementSerializer)
391
}
392
}
393
}
394
395
// Usage with built-in serializers
396
val customStringCollectionSerializer = CustomCollection.serializer(String.serializer())
397
val customUserCollectionSerializer = CustomCollection.serializer(User.serializer())
398
```
399
400
Built-in serializers provide the foundation for serializing most common Kotlin types. They can be composed to handle complex nested data structures while maintaining type safety and performance.