0
# Built-in Serializers
1
2
Complete reference for all built-in serializers provided by kotlinx.serialization-core-js for standard Kotlin types.
3
4
## Primitive Type Serializers
5
6
### Companion Object Serializers
7
8
All primitive types provide serializers through their companion objects.
9
10
```kotlin
11
val Char.Companion.serializer: KSerializer<Char>
12
val Byte.Companion.serializer: KSerializer<Byte>
13
val Short.Companion.serializer: KSerializer<Short>
14
val Int.Companion.serializer: KSerializer<Int>
15
val Long.Companion.serializer: KSerializer<Long>
16
val Float.Companion.serializer: KSerializer<Float>
17
val Double.Companion.serializer: KSerializer<Double>
18
val Boolean.Companion.serializer: KSerializer<Boolean>
19
val String.Companion.serializer: KSerializer<String>
20
val Unit.serializer: KSerializer<Unit>
21
```
22
{ .api }
23
24
**Usage:**
25
26
```javascript
27
// Access primitive serializers
28
const charSerializer = Char.serializer();
29
const byteSerializer = Byte.serializer();
30
const shortSerializer = Short.serializer();
31
const intSerializer = Int.serializer();
32
const longSerializer = Long.serializer();
33
const floatSerializer = Float.serializer();
34
const doubleSerializer = Double.serializer();
35
const booleanSerializer = Boolean.serializer();
36
const stringSerializer = String.serializer();
37
const unitSerializer = Unit.serializer();
38
39
// Use with any format
40
const json = format.encodeToString(Int.serializer(), 42);
41
const number = format.decodeFromString(Int.serializer(), json);
42
```
43
44
### Unsigned Type Serializers
45
46
Serializers for unsigned integer types.
47
48
```kotlin
49
val UByte.Companion.serializer: KSerializer<UByte>
50
val UShort.Companion.serializer: KSerializer<UShort>
51
val UInt.Companion.serializer: KSerializer<UInt>
52
val ULong.Companion.serializer: KSerializer<ULong>
53
```
54
{ .api }
55
56
**Usage:**
57
58
```javascript
59
// Unsigned type serializers
60
const ubyteSerializer = UByte.serializer();
61
const ushortSerializer = UShort.serializer();
62
const uintSerializer = UInt.serializer();
63
const ulongSerializer = ULong.serializer();
64
65
// Example usage
66
const value = 42u;
67
const serialized = format.encodeToString(UInt.serializer(), value);
68
```
69
70
## Nullable Serializers
71
72
### .nullable Property
73
74
Any serializer can be made nullable using the `.nullable` property.
75
76
```kotlin
77
val KSerializer<T>.nullable: KSerializer<T?>
78
```
79
{ .api }
80
81
**Usage:**
82
83
```javascript
84
// Create nullable serializers
85
const nullableString = String.serializer().nullable;
86
const nullableInt = Int.serializer().nullable;
87
const nullableUser = User.serializer().nullable;
88
89
// Serialize nullable values
90
const json1 = format.encodeToString(nullableString, "hello"); // "hello"
91
const json2 = format.encodeToString(nullableString, null); // null
92
93
// Deserialize nullable values
94
const str1 = format.decodeFromString(nullableString, '"hello"'); // "hello"
95
const str2 = format.decodeFromString(nullableString, 'null'); // null
96
```
97
98
## Collection Serializers
99
100
### List Serializer
101
102
Factory function for creating List serializers.
103
104
```kotlin
105
fun <T> ListSerializer(elementSerializer: KSerializer<T>): KSerializer<List<T>>
106
```
107
{ .api }
108
109
**Usage:**
110
111
```javascript
112
// Create list serializers
113
const stringListSerializer = ListSerializer(String.serializer());
114
const intListSerializer = ListSerializer(Int.serializer());
115
const userListSerializer = ListSerializer(User.serializer());
116
117
// Nested collections
118
const nestedListSerializer = ListSerializer(ListSerializer(String.serializer()));
119
120
// Usage
121
const names = ["Alice", "Bob", "Charlie"];
122
const json = format.encodeToString(stringListSerializer, names);
123
// Output: ["Alice","Bob","Charlie"]
124
125
const deserializedNames = format.decodeFromString(stringListSerializer, json);
126
```
127
128
### Set Serializer
129
130
Factory function for creating Set serializers.
131
132
```kotlin
133
fun <T> SetSerializer(elementSerializer: KSerializer<T>): KSerializer<Set<T>>
134
```
135
{ .api }
136
137
**Usage:**
138
139
```javascript
140
// Create set serializers
141
const stringSetSerializer = SetSerializer(String.serializer());
142
const intSetSerializer = SetSerializer(Int.serializer());
143
144
// Usage
145
const uniqueNumbers = new Set([1, 2, 3, 3, 4]); // Set with 4 unique elements
146
const json = format.encodeToString(intSetSerializer, uniqueNumbers);
147
const deserializedSet = format.decodeFromString(intSetSerializer, json);
148
```
149
150
### Map Serializer
151
152
Factory function for creating Map serializers.
153
154
```kotlin
155
fun <K, V> MapSerializer(
156
keySerializer: KSerializer<K>,
157
valueSerializer: KSerializer<V>
158
): KSerializer<Map<K, V>>
159
```
160
{ .api }
161
162
**Usage:**
163
164
```javascript
165
// Create map serializers
166
const stringIntMapSerializer = MapSerializer(String.serializer(), Int.serializer());
167
const intUserMapSerializer = MapSerializer(Int.serializer(), User.serializer());
168
169
// Complex maps
170
const mapOfListsSerializer = MapSerializer(
171
String.serializer(),
172
ListSerializer(Int.serializer())
173
);
174
175
// Usage
176
const scores = new Map([
177
["Alice", 95],
178
["Bob", 87],
179
["Charlie", 92]
180
]);
181
182
const json = format.encodeToString(stringIntMapSerializer, scores);
183
const deserializedScores = format.decodeFromString(stringIntMapSerializer, json);
184
```
185
186
## Pair and Triple Serializers
187
188
### Pair Serializer
189
190
Factory function for creating Pair serializers.
191
192
```kotlin
193
fun <A, B> PairSerializer(
194
aSerializer: KSerializer<A>,
195
bSerializer: KSerializer<B>
196
): KSerializer<Pair<A, B>>
197
```
198
{ .api }
199
200
**Usage:**
201
202
```javascript
203
// Create pair serializer
204
const stringIntPairSerializer = PairSerializer(String.serializer(), Int.serializer());
205
206
// Usage
207
const coordinate = new Pair("x", 10);
208
const json = format.encodeToString(stringIntPairSerializer, coordinate);
209
const deserializedCoordinate = format.decodeFromString(stringIntPairSerializer, json);
210
```
211
212
### MapEntry Serializer
213
214
Factory function for creating Map.Entry serializers.
215
216
```kotlin
217
fun <K, V> MapEntrySerializer(
218
keySerializer: KSerializer<K>,
219
valueSerializer: KSerializer<V>
220
): KSerializer<Map.Entry<K, V>>
221
```
222
{ .api }
223
224
**Usage:**
225
226
```javascript
227
// Create map entry serializer
228
const stringIntEntrySerializer = MapEntrySerializer(String.serializer(), Int.serializer());
229
230
// Usage with map entries
231
const map = new Map([["key", 42]]);
232
const entry = map.entries().next().value;
233
const json = format.encodeToString(stringIntEntrySerializer, entry);
234
```
235
236
### Triple Serializer
237
238
Factory function for creating Triple serializers.
239
240
```kotlin
241
fun <A, B, C> TripleSerializer(
242
aSerializer: KSerializer<A>,
243
bSerializer: KSerializer<B>,
244
cSerializer: KSerializer<C>
245
): KSerializer<Triple<A, B, C>>
246
```
247
{ .api }
248
249
**Usage:**
250
251
```javascript
252
// Create triple serializer
253
const stringIntBoolTripleSerializer = TripleSerializer(
254
String.serializer(),
255
Int.serializer(),
256
Boolean.serializer()
257
);
258
259
// Usage
260
const coordinate3D = new Triple("point", 10, true);
261
const json = format.encodeToString(stringIntBoolTripleSerializer, coordinate3D);
262
```
263
264
## Array Serializers
265
266
### Reference Array Serializer
267
268
Factory functions for creating Array serializers (Experimental).
269
270
```kotlin
271
@ExperimentalSerializationApi
272
inline fun <reified T, reified E : T> ArraySerializer(
273
elementSerializer: KSerializer<E>
274
): KSerializer<Array<T>>
275
276
@ExperimentalSerializationApi
277
fun <T> ArraySerializer(
278
kClass: KClass<T>,
279
elementSerializer: KSerializer<T>
280
): KSerializer<Array<T>>
281
```
282
{ .api }
283
284
**Usage:**
285
286
```javascript
287
// Create array serializers
288
const stringArraySerializer = ArraySerializer(String.serializer());
289
const userArraySerializer = ArraySerializer(User::class, User.serializer());
290
291
// Usage
292
const names = ["Alice", "Bob", "Charlie"];
293
const json = format.encodeToString(stringArraySerializer, names);
294
const deserializedArray = format.decodeFromString(stringArraySerializer, json);
295
```
296
297
### Primitive Array Serializers
298
299
Specialized serializers for primitive arrays.
300
301
```kotlin
302
fun CharArraySerializer(): KSerializer<CharArray>
303
fun ByteArraySerializer(): KSerializer<ByteArray>
304
fun ShortArraySerializer(): KSerializer<ShortArray>
305
fun IntArraySerializer(): KSerializer<IntArray>
306
fun LongArraySerializer(): KSerializer<LongArray>
307
fun FloatArraySerializer(): KSerializer<FloatArray>
308
fun DoubleArraySerializer(): KSerializer<DoubleArray>
309
fun BooleanArraySerializer(): KSerializer<BooleanArray>
310
```
311
{ .api }
312
313
**Usage:**
314
315
```javascript
316
// Primitive array serializers
317
const charArraySer = CharArraySerializer();
318
const byteArraySer = ByteArraySerializer();
319
const shortArraySer = ShortArraySerializer();
320
const intArraySer = IntArraySerializer();
321
const longArraySer = LongArraySerializer();
322
const floatArraySer = FloatArraySerializer();
323
const doubleArraySer = DoubleArraySerializer();
324
const booleanArraySer = BooleanArraySerializer();
325
326
// Usage examples
327
const numbers = new Int32Array([1, 2, 3, 4, 5]);
328
const json = format.encodeToString(intArraySer, numbers);
329
const deserializedNumbers = format.decodeFromString(intArraySer, json);
330
331
const bytes = new Uint8Array([65, 66, 67]); // "ABC" in ASCII
332
const byteJson = format.encodeToString(byteArraySer, bytes);
333
```
334
335
### Unsigned Array Serializers
336
337
Serializers for unsigned primitive arrays (Experimental).
338
339
```kotlin
340
@ExperimentalSerializationApi
341
fun UByteArraySerializer(): KSerializer<UByteArray>
342
343
@ExperimentalSerializationApi
344
fun UShortArraySerializer(): KSerializer<UShortArray>
345
346
@ExperimentalSerializationApi
347
fun UIntArraySerializer(): KSerializer<UIntArray>
348
349
@ExperimentalSerializationApi
350
fun ULongArraySerializer(): KSerializer<ULongArray>
351
```
352
{ .api }
353
354
**Usage:**
355
356
```javascript
357
// Unsigned array serializers (experimental)
358
const ubyteArraySer = UByteArraySerializer();
359
const ushortArraySer = UShortArraySerializer();
360
const uintArraySer = UIntArraySerializer();
361
const ulongArraySer = ULongArraySerializer();
362
363
// Usage
364
const unsignedInts = new Uint32Array([1u, 2u, 3u]);
365
const json = format.encodeToString(uintArraySer, unsignedInts);
366
```
367
368
## Time and Duration Serializers
369
370
### Duration Serializer
371
372
Serializer for kotlin.time.Duration.
373
374
```kotlin
375
val Duration.Companion.serializer: KSerializer<Duration>
376
```
377
{ .api }
378
379
**Usage:**
380
381
```javascript
382
const durationSerializer = Duration.serializer();
383
384
// Usage with durations
385
const duration = Duration.ofSeconds(30);
386
const json = format.encodeToString(durationSerializer, duration);
387
const deserializedDuration = format.decodeFromString(durationSerializer, json);
388
389
// In serializable classes
390
@Serializable
391
class Task {
392
name;
393
timeout; // Duration type, automatically uses Duration.serializer()
394
395
constructor(name, timeout) {
396
this.name = name;
397
this.timeout = timeout;
398
}
399
}
400
```
401
402
### Instant Serializer
403
404
Serializer for kotlinx.datetime.Instant (Experimental).
405
406
```kotlin
407
@ExperimentalSerializationApi
408
val Instant.Companion.serializer: KSerializer<Instant>
409
```
410
{ .api }
411
412
**Usage:**
413
414
```javascript
415
const instantSerializer = Instant.serializer();
416
417
// Usage with instants
418
const now = Instant.now();
419
const json = format.encodeToString(instantSerializer, now);
420
const deserializedInstant = format.decodeFromString(instantSerializer, json);
421
```
422
423
### Instant Component Serializer
424
425
Alternative serializer that represents Instant as epoch components (Experimental).
426
427
```kotlin
428
@ExperimentalSerializationApi
429
object InstantComponentSerializer : KSerializer<Instant>
430
```
431
{ .api }
432
433
**Usage:**
434
435
```javascript
436
// Use component-based instant serialization
437
@Serializable
438
class Event {
439
name;
440
441
@Serializable(InstantComponentSerializer::class)
442
timestamp; // Serialized as {epochSeconds: 1234567890, nanosecondsOfSecond: 123456789}
443
444
constructor(name, timestamp) {
445
this.name = name;
446
this.timestamp = timestamp;
447
}
448
}
449
```
450
451
## UUID Serializer
452
453
### Uuid Serializer
454
455
Serializer for UUID values (Experimental).
456
457
```kotlin
458
@ExperimentalSerializationApi
459
val Uuid.Companion.serializer: KSerializer<Uuid>
460
```
461
{ .api }
462
463
**Usage:**
464
465
```javascript
466
const uuidSerializer = Uuid.serializer();
467
468
// Usage with UUIDs
469
const id = Uuid.random();
470
const json = format.encodeToString(uuidSerializer, id);
471
const deserializedUuid = format.decodeFromString(uuidSerializer, json);
472
473
// In data classes
474
@Serializable
475
class Document {
476
@Serializable(Uuid.serializer()::class)
477
id; // UUID
478
479
title;
480
481
constructor(id, title) {
482
this.id = id;
483
this.title = title;
484
}
485
}
486
```
487
488
## JavaScript-Specific Serializers
489
490
### Long as String Serializer
491
492
Special serializer for Long values that serializes them as strings to avoid JavaScript precision issues.
493
494
```kotlin
495
object LongAsStringSerializer : KSerializer<Long>
496
```
497
{ .api }
498
499
**Usage:**
500
501
```javascript
502
// Use for JavaScript interoperability
503
@Serializable
504
class Transaction {
505
@Serializable(LongAsStringSerializer::class)
506
amount; // Serialized as "1234567890123456789" instead of number
507
508
description;
509
510
constructor(amount, description) {
511
this.amount = amount;
512
this.description = description;
513
}
514
}
515
516
// Direct usage
517
const longValue = 9007199254740991L; // Larger than MAX_SAFE_INTEGER
518
const json = format.encodeToString(LongAsStringSerializer, longValue);
519
// Output: "9007199254740991"
520
521
const deserializedLong = format.decodeFromString(LongAsStringSerializer, json);
522
```
523
524
## Nothing Serializer
525
526
### NothingSerializer
527
528
Serializer for the Nothing type that always throws (Experimental).
529
530
```kotlin
531
@ExperimentalSerializationApi
532
fun NothingSerializer(): KSerializer<Nothing>
533
```
534
{ .api }
535
536
**Usage:**
537
538
```javascript
539
const nothingSerializer = NothingSerializer();
540
541
// This will always throw SerializationException
542
try {
543
format.encodeToString(nothingSerializer, /* any value */);
544
} catch (e) {
545
console.log("Nothing cannot be serialized:", e.message);
546
}
547
548
// Useful for sealed class exhaustiveness
549
@Serializable
550
sealed class Result<T> {
551
@Serializable
552
static class Success<T> extends Result<T> {
553
constructor(value) {
554
super();
555
this.value = value;
556
}
557
}
558
559
@Serializable
560
static class Error extends Result {
561
constructor(message) {
562
super();
563
this.message = message;
564
}
565
}
566
567
// This ensures all cases are covered in pattern matching
568
static neverCase() {
569
return NothingSerializer();
570
}
571
}
572
```
573
574
## Custom Collection Types
575
576
### Creating Custom Collection Serializers
577
578
```javascript
579
// Custom collection serializer example
580
class ImmutableListSerializer {
581
constructor(elementSerializer) {
582
this.elementSerializer = elementSerializer;
583
this.descriptor = ListSerializer(elementSerializer).descriptor;
584
}
585
586
serialize(encoder, value) {
587
// Convert ImmutableList to regular array for serialization
588
const array = value.toArray();
589
const listSerializer = ListSerializer(this.elementSerializer);
590
listSerializer.serialize(encoder, array);
591
}
592
593
deserialize(decoder) {
594
// Deserialize as array then convert to ImmutableList
595
const listSerializer = ListSerializer(this.elementSerializer);
596
const array = listSerializer.deserialize(decoder);
597
return ImmutableList.from(array);
598
}
599
}
600
601
// Usage
602
const immutableStringListSerializer = new ImmutableListSerializer(String.serializer());
603
604
@Serializable
605
class DataContainer {
606
@Serializable(ImmutableListSerializer<String>::class)
607
items;
608
609
constructor(items) {
610
this.items = items;
611
}
612
}
613
```
614
615
## Serializer Registration
616
617
### Using Built-in Serializers in Modules
618
619
```javascript
620
// Register built-in serializers in modules
621
const module = SerializersModule {
622
// Contextual serializers for special handling
623
contextual(Long::class, LongAsStringSerializer)
624
contextual(Instant::class, InstantComponentSerializer)
625
626
// Custom serializers for third-party types
627
contextual(BigDecimal::class, BigDecimalStringSerializer)
628
};
629
630
// Use with format
631
const format = Json {
632
serializersModule = module
633
};
634
635
@Serializable
636
class FinancialRecord {
637
@Contextual
638
amount; // Uses LongAsStringSerializer from module
639
640
@Contextual
641
timestamp; // Uses InstantComponentSerializer from module
642
643
constructor(amount, timestamp) {
644
this.amount = amount;
645
this.timestamp = timestamp;
646
}
647
}
648
```
649
650
## Type-Safe Generic Serializers
651
652
### Generic Factory Functions
653
654
```typescript
655
// Type-safe generic serializer factories
656
function createListSerializer<T>(elementSerializer: KSerializer<T>): KSerializer<Array<T>> {
657
return ListSerializer(elementSerializer);
658
}
659
660
function createMapSerializer<K, V>(
661
keySerializer: KSerializer<K>,
662
valueSerializer: KSerializer<V>
663
): KSerializer<Map<K, V>> {
664
return MapSerializer(keySerializer, valueSerializer);
665
}
666
667
// Usage with full type safety
668
const userListSerializer: KSerializer<Array<User>> = createListSerializer(User.serializer());
669
const stringIntMapSerializer: KSerializer<Map<string, number>> = createMapSerializer(
670
String.serializer(),
671
Int.serializer()
672
);
673
```
674
675
The built-in serializers provide comprehensive support for all standard Kotlin types and collections, enabling seamless serialization of complex data structures while maintaining type safety and JavaScript interoperability.