summaryrefslogtreecommitdiff
path: root/docs/serializers.md
blob: fc4e1a60af1a101ccda5cfcf7029a5532f426233 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
<!--- TEST_NAME SerializersTest -->

# Serializers

This is the third chapter of the [Kotlin Serialization Guide](serialization-guide.md).
In this chapter we'll take a look at serializers in more detail, and we'll see how custom serializers can be written.

**Table of contents**

<!--- TOC -->

* [Introduction to serializers](#introduction-to-serializers)
  * [Plugin-generated serializer](#plugin-generated-serializer)
  * [Plugin-generated generic serializer](#plugin-generated-generic-serializer)
  * [Builtin primitive serializers](#builtin-primitive-serializers)
  * [Constructing collection serializers](#constructing-collection-serializers)
  * [Using top-level serializer function](#using-top-level-serializer-function)
* [Custom serializers](#custom-serializers)
  * [Primitive serializer](#primitive-serializer)
  * [Delegating serializers](#delegating-serializers)
  * [Composite serializer via surrogate](#composite-serializer-via-surrogate)
  * [Hand-written composite serializer](#hand-written-composite-serializer)
  * [Sequential decoding protocol (experimental)](#sequential-decoding-protocol-experimental)
  * [Serializing 3rd party classes](#serializing-3rd-party-classes)
  * [Passing a serializer manually](#passing-a-serializer-manually)
  * [Specifying serializer on a property](#specifying-serializer-on-a-property)
  * [Specifying serializers for a file](#specifying-serializers-for-a-file)
  * [Custom serializers for a generic type](#custom-serializers-for-a-generic-type)
  * [Format-specific serializers](#format-specific-serializers)
* [Contextual serialization](#contextual-serialization)
  * [Serializers module](#serializers-module)
  * [Contextual serialization and generic classes](#contextual-serialization-and-generic-classes)
* [Deriving external serializer for another Kotlin class (experimental)](#deriving-external-serializer-for-another-kotlin-class-experimental)
  * [External serialization uses properties](#external-serialization-uses-properties)

<!--- END -->

## Introduction to serializers

Formats, like JSON, control the _encoding_ of an object into specific output bytes, but how the object is decomposed 
into its constituent properties is controlled by a _serializer_. So far we've been using automatically-derived
serializers by using the [`@Serializable`][Serializable] annotation as explained in 
the [Serializable classes](/docs/basic-serialization.md#serializable-classes) section, or using builtin serializers that were shown in 
the [Builtin classes](/docs/builtin-classes.md) section.

As a motivating example, let us take the following `Color` class with an integer value storing its `rgb` bytes.

<!--- INCLUDE
import kotlinx.serialization.*
import kotlinx.serialization.json.*
-->

```kotlin
@Serializable
class Color(val rgb: Int)

fun main() {
    val green = Color(0x00ff00)
    println(Json.encodeToString(green))
}  
```              

> You can get the full code [here](../guide/example/example-serializer-01.kt).

By default this class serializes its `rgb` property into JSON.

```text
{"rgb":65280}
```     

<!--- TEST -->

### Plugin-generated serializer

Every class marked with the `@Serializable` annotation, like the `Color` class from the previous example,
gets an instance of the [KSerializer] interface automatically generated by the Kotlin Serialization compiler plugin.
We can retrieve this instance using the `.serializer()` function on the class's companion object.

We can examine its [descriptor][KSerializer.descriptor] property that describes the structure of 
the serialized class. We'll learn more details about that in the upcoming sections.

<!--- INCLUDE 
import kotlinx.serialization.*

@Serializable
@SerialName("Color")
class Color(val rgb: Int)
-->

```kotlin
fun main() {
    val colorSerializer: KSerializer<Color> = Color.serializer()
    println(colorSerializer.descriptor)
} 
```             

> You can get the full code [here](../guide/example/example-serializer-02.kt).

```text
Color(rgb: kotlin.Int)
```

<!--- TEST -->

This serializer is automatically retrieved and used by the Kotlin Serialization framework when the `Color` class 
is itself serialized, or when it is used as a property of other classes.

> You cannot define your own function `serializer()` on a companion object of a serializable class. 

### Plugin-generated generic serializer

For generic classes, like the `Box` class shown in the [Generic classes](basic-serialization.md#generic-classes) section,
the automatically generated `.serializer()` function accepts as many parameters as there are type parameters in the 
corresponding class. These parameters are of type [KSerializer], so the actual type argument's serializer has 
to be provided when constructing an instance of a serializer for a generic class.

<!--- INCLUDE 
import kotlinx.serialization.*

@Serializable
@SerialName("Color")
class Color(val rgb: Int)
-->

```kotlin
@Serializable           
@SerialName("Box")
class Box<T>(val contents: T)    

fun main() {
    val boxedColorSerializer = Box.serializer(Color.serializer())
    println(boxedColorSerializer.descriptor)
} 
```      

> You can get the full code [here](../guide/example/example-serializer-03.kt).                                                     

As we can see, a serializer was instantiated to serialize a concrete `Box<Color>`.

```text 
Box(contents: Color)
```       

<!--- TEST -->

### Builtin primitive serializers

The serializers for the [primitive builtin classes](builtin-classes.md#primitives) can be retrieved
using `.serializer()` extensions. 

<!--- INCLUDE
import kotlinx.serialization.*
import kotlinx.serialization.builtins.*
-->

```kotlin 
fun main() {
    val intSerializer: KSerializer<Int> = Int.serializer()
    println(intSerializer.descriptor)
}
```

> You can get the full code [here](../guide/example/example-serializer-04.kt).   

<!--- TEST 
PrimitiveDescriptor(kotlin.Int)
--> 

### Constructing collection serializers

[Builtin collection serializers](builtin-classes.md#lists), when needed, must be explicitly constructed
using the corresponding functions [ListSerializer()], [SetSerializer()], [MapSerializer()], etc.
These classes are generic, so to instantiate their serializer we must provide the serializers for the
corresponding number of their type parameters.
For example, we can produce a serializer for a `List<String>` in the following way.

<!--- INCLUDE
import kotlinx.serialization.*
import kotlinx.serialization.builtins.*
-->

```kotlin 
fun main() {   
    val stringListSerializer: KSerializer<List<String>> = ListSerializer(String.serializer()) 
    println(stringListSerializer.descriptor)
}
```

> You can get the full code [here](../guide/example/example-serializer-05.kt).  

<!--- TEST 
kotlin.collections.ArrayList(PrimitiveDescriptor(kotlin.String))
--> 

### Using top-level serializer function

When in doubt, you can always use the top-level generic `serializer<T>()`
function to retrieve a serializer for an arbitrary Kotlin type in your source-code.

<!--- INCLUDE
import kotlinx.serialization.*
-->

```kotlin 
@Serializable            
@SerialName("Color")
class Color(val rgb: Int)

fun main() {        
    val stringToColorMapSerializer: KSerializer<Map<String, Color>> = serializer()
    println(stringToColorMapSerializer.descriptor)
}
```

> You can get the full code [here](../guide/example/example-serializer-06.kt).  

<!--- TEST 
kotlin.collections.LinkedHashMap(PrimitiveDescriptor(kotlin.String), Color(rgb: kotlin.Int))
--> 

## Custom serializers

A plugin-generated serializer is convenient, but it may not produce the JSON we want 
for such a class as `Color`. Let's study alternatives.

### Primitive serializer

We want to serialize the `Color` class as a hex string with the green color represented as `"00ff00"`.
To achieve this, we write an object that implements the [KSerializer] interface for the `Color` class.

<!--- INCLUDE .*-serializer-.*
import kotlinx.serialization.*
import kotlinx.serialization.json.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.descriptors.*
-->

```kotlin
object ColorAsStringSerializer : KSerializer<Color> {
    override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Color", PrimitiveKind.STRING)

    override fun serialize(encoder: Encoder, value: Color) {
        val string = value.rgb.toString(16).padStart(6, '0')
        encoder.encodeString(string)
    }

    override fun deserialize(decoder: Decoder): Color {
        val string = decoder.decodeString()
        return Color(string.toInt(16))
    }
}
```

Serializer has three required pieces. 

* The [serialize][SerializationStrategy.serialize] function implements [SerializationStrategy].
  It receives an instance of [Encoder] and a value to serialize.
  It uses the `encodeXxx` functions of `Encoder` to represent a value as a sequence of primitives. There is an 
  `encodeXxx` for each primitive type supported by serialization. 
  In our example, [encodeString][Encoder.encodeString] is used.
  
* The [deserialize][DeserializationStrategy.deserialize] function implements [DeserializationStrategy].
  It receives an instance of [Decoder] and returns a 
  deserialized value. It uses the `decodeXxx` functions of `Decoder`, which mirror the corresponding functions of `Encoder`.
  In our example [decodeString][Decoder.decodeString] is used.
  
* The [descriptor][KSerializer.descriptor] property must faithfully explain what exactly the `encodeXxx` and `decodeXxx` 
  functions do so that a format implementation knows in advance what encoding/decoding methods they call. 
  Some formats might also use it to generate a schema for the serialized data. For primitive serialization, 
  the [PrimitiveSerialDescriptor][PrimitiveSerialDescriptor()] function must be used with a unique name of the 
  type that is being serialized.
  [PrimitiveKind] describes the specific `encodeXxx`/`decodeXxx` method that is being used in the implementation.
  
> When the `descriptor` does not correspond to the encoding/decoding methods, then the behavior of the resulting code
> is unspecified, and may arbitrarily change in future updates.        
  
The next step is to bind a serializer to a class. This is done with the [`@Serializable`][Serializable] annotation by adding
the [`with`][Serializable.with] property value.

```kotlin
@Serializable(with = ColorAsStringSerializer::class)
class Color(val rgb: Int)
```  

Now we can serialize the `Color` class as we did before.

```kotlin
fun main() {
    val green = Color(0x00ff00)
    println(Json.encodeToString(green))
}  
```              

> You can get the full code [here](../guide/example/example-serializer-07.kt).

We get the serial representation as the hex string we wanted.

```text
"00ff00"
```                        

<!--- TEST -->    

Deserialization is also straightforward because we implemented the `deserialize` method.

<!--- INCLUDE 
object ColorAsStringSerializer : KSerializer<Color> {
    override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Color", PrimitiveKind.STRING)

    override fun serialize(encoder: Encoder, value: Color) {
        val string = value.rgb.toString(16).padStart(6, '0')
        encoder.encodeString(string)
    }

    override fun deserialize(decoder: Decoder): Color {
        val string = decoder.decodeString()
        return Color(string.toInt(16))
    }
}
-->

```kotlin
@Serializable(with = ColorAsStringSerializer::class)
class Color(val rgb: Int)

fun main() {
    val color = Json.decodeFromString<Color>("\"00ff00\"")
    println(color.rgb) // prints 65280 
}  
```     

> You can get the full code [here](../guide/example/example-serializer-08.kt).

<!--- TEST 
65280
-->

It also works if we serialize or deserialize a different class with `Color` properties.

<!--- INCLUDE 
object ColorAsStringSerializer : KSerializer<Color> {
    override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Color", PrimitiveKind.STRING)

    override fun serialize(encoder: Encoder, value: Color) {
        val string = value.rgb.toString(16).padStart(6, '0')
        encoder.encodeString(string)
    }

    override fun deserialize(decoder: Decoder): Color {
        val string = decoder.decodeString()
        return Color(string.toInt(16))
    }
}
-->

```kotlin
@Serializable(with = ColorAsStringSerializer::class)
data class Color(val rgb: Int)

@Serializable 
data class Settings(val background: Color, val foreground: Color)

fun main() {
    val data = Settings(Color(0xffffff), Color(0))
    val string = Json.encodeToString(data)
    println(string)
    require(Json.decodeFromString<Settings>(string) == data)
}  
```     

> You can get the full code [here](../guide/example/example-serializer-09.kt).

Both `Color` properties are serialized as strings.

```text 
{"background":"ffffff","foreground":"000000"}
```

<!--- TEST -->

### Delegating serializers

In the previous example, we represented the `Color` class as a string.
String is considered to be a primitive type, therefore we used `PrimitiveClassDescriptor` and specialized `encodeString` method. 
Now let's see what our actions would be if we have to serialize `Color` as another non-primitive type, let's say `IntArray`.

An implementation of [KSerializer] for our original `Color` class is going to perform a conversion between
`Color` and `IntArray`, but delegate the actual serialization logic to the `IntArraySerializer`
using [encodeSerializableValue][Encoder.encodeSerializableValue] and
[decodeSerializableValue][Decoder.decodeSerializableValue].

```kotlin
import kotlinx.serialization.builtins.IntArraySerializer

class ColorIntArraySerializer : KSerializer<Color> {
    private val delegateSerializer = IntArraySerializer()
    override val descriptor = SerialDescriptor("Color", delegateSerializer.descriptor)

    override fun serialize(encoder: Encoder, value: Color) {
        val data = intArrayOf(
            (value.rgb shr 16) and 0xFF,
            (value.rgb shr 8) and 0xFF,
            value.rgb and 0xFF
        )
        encoder.encodeSerializableValue(delegateSerializer, data)
    }

    override fun deserialize(decoder: Decoder): Color {
        val array = decoder.decodeSerializableValue(delegateSerializer)
        return Color((array[0] shl 16) or (array[1] shl 8) or array[2])
    }
}
```

Note that we can't use default `Color.serializer().descriptor` here because formats that rely
on the schema may think that we would call `encodeInt` instead of `encodeSerializableValue`.
Neither we can use `IntArraySerializer().descriptor` directly — otherwise, formats that handle int arrays specially
can't tell if `value` is really a `IntArray` or a `Color`. Don't worry, this optimization would still kick in
when serializing actual underlying int array.

> Example of how format can treat arrays specially is shown in the [formats guide](formats.md#format-specific-types).

Now we can use the serializer:

```kotlin
@Serializable(with = ColorIntArraySerializer::class)
class Color(val rgb: Int)

fun main() {
    val green = Color(0x00ff00)
    println(Json.encodeToString(green))
}  
```    

As you can see, such array representation is not very useful in JSON,
but may save some space when used with a `ByteArray` and a binary format.

> You can get the full code [here](../guide/example/example-serializer-10.kt).

```text
[0,255,0]
```

<!--- TEST -->


### Composite serializer via surrogate

Now our challenge is to get `Color` serialized so that it is represented in JSON as if it is a class 
with three properties&mdash;`r`, `g`, and `b`&mdash;so that JSON encodes it as an object. 
The easiest way to achieve this is to define a _surrogate_ class mimicking the serialized form of `Color` that
we are going to use for its serialization. We also set the [SerialName] of this surrogate class to `Color`. Then if 
any format uses this name the surrogate looks like it is a `Color` class.
The surrogate class can be `private`, and can enforce all the constraints on the serial representation 
of the class in its `init` block.

```kotlin
@Serializable
@SerialName("Color")
private class ColorSurrogate(val r: Int, val g: Int, val b: Int) {
    init {     
        require(r in 0..255 && g in 0..255 && b in 0..255)
    }
}
```

> An example of where the class name is used is shown in 
> the [Custom subclass serial name](polymorphism.md#custom-subclass-serial-name) section in the chapter on polymorphism.
  
Now we can use the `ColorSurrogate.serializer()` function to retrieve a plugin-generated serializer for the
surrogate class.

We can use the same approach as in [delegating serializer](#delegating-serializers), but this time,
we are fully reusing an automatically
generated [SerialDescriptor] for the surrogate because it should be indistinguishable from the original.

```kotlin
object ColorSerializer : KSerializer<Color> {
    override val descriptor: SerialDescriptor = ColorSurrogate.serializer().descriptor

    override fun serialize(encoder: Encoder, value: Color) {
        val surrogate = ColorSurrogate((value.rgb shr 16) and 0xff, (value.rgb shr 8) and 0xff, value.rgb and 0xff)
        encoder.encodeSerializableValue(ColorSurrogate.serializer(), surrogate)
    }

    override fun deserialize(decoder: Decoder): Color {
        val surrogate = decoder.decodeSerializableValue(ColorSurrogate.serializer())
        return Color((surrogate.r shl 16) or (surrogate.g shl 8) or surrogate.b)
    }
}
```
 
We bind the `ColorSerializer` serializer to the `Color` class.

```kotlin
@Serializable(with = ColorSerializer::class)
class Color(val rgb: Int)
```  

Now we can enjoy the result of serialization for the `Color` class.

<!--- INCLUDE
fun main() {
    val green = Color(0x00ff00)
    println(Json.encodeToString(green))
}
-->

> You can get the full code [here](../guide/example/example-serializer-11.kt).

```text
{"r":0,"g":255,"b":0}
```                        

<!--- TEST -->    

### Hand-written composite serializer

There are some cases where a surrogate solution does not fit. Perhaps we want to avoid the performance 
implications of additional allocation, or we want a configurable/dynamic set of properties for the 
resulting serial representation. In these cases we need to manually write a class
serializer which mimics the behaviour of a generated serializer. 

```kotlin 
object ColorAsObjectSerializer : KSerializer<Color> {
```

Let's introduce it piece by piece. First, a descriptor is defined using the [buildClassSerialDescriptor] builder.
The [element][ClassSerialDescriptorBuilder.element] function in the builder DSL automatically fetches serializers
for the corresponding fields by their type. The order of elements is important. They are indexed starting from zero.

```kotlin
    override val descriptor: SerialDescriptor =
        buildClassSerialDescriptor("Color") {
            element<Int>("r")
            element<Int>("g")
            element<Int>("b")
        }
```                                                                        

> The "element" is a generic term here. What is an element of a descriptor depends on its [SerialKind]. 
> Elements of a class descriptor are its properties, elements of a enum descriptor are its cases, etc.

Then we write the `serialize` function using the [encodeStructure] DSL that provides access to 
the [CompositeEncoder] in its block. The difference between [Encoder] and [CompositeEncoder] is the latter
has `encodeXxxElement` functions that correspond to the `encodeXxx` functions of the former. They must be called
in the same order as in the descriptor. 

```kotlin
    override fun serialize(encoder: Encoder, value: Color) =
        encoder.encodeStructure(descriptor) {
            encodeIntElement(descriptor, 0, (value.rgb shr 16) and 0xff)
            encodeIntElement(descriptor, 1, (value.rgb shr 8) and 0xff)
            encodeIntElement(descriptor, 2, value.rgb and 0xff)
        }
```                                     

The most complex piece of code is the `deserialize` function. It must support formats, like JSON, that 
can decode properties in an arbitrary order. It starts with the call to [decodeStructure] to 
get access to a [CompositeDecoder]. Inside it we write a loop that repeatedly calls 
[decodeElementIndex][CompositeDecoder.decodeElementIndex] to decode the index of the next element, then we decode the corresponding
element using [decodeIntElement][CompositeDecoder.decodeIntElement] in our example, and finally we terminate the loop when
`CompositeDecoder.DECODE_DONE` is encountered.

```kotlin
    override fun deserialize(decoder: Decoder): Color =
        decoder.decodeStructure(descriptor) {
            var r = -1
            var g = -1
            var b = -1
            while (true) {
                when (val index = decodeElementIndex(descriptor)) {
                    0 -> r = decodeIntElement(descriptor, 0)
                    1 -> g = decodeIntElement(descriptor, 1)
                    2 -> b = decodeIntElement(descriptor, 2)
                    CompositeDecoder.DECODE_DONE -> break
                    else -> error("Unexpected index: $index")
                }
            }
            require(r in 0..255 && g in 0..255 && b in 0..255)
            Color((r shl 16) or (g shl 8) or b)
        }
```

<!--- INCLUDE
}
-->
  
Now we bind the resulting serializer to the `Color` class and test its serialization/deserialization.

```kotlin   
@Serializable(with = ColorAsObjectSerializer::class)
data class Color(val rgb: Int)

fun main() {
    val color = Color(0x00ff00)
    val string = Json.encodeToString(color) 
    println(string)
    require(Json.decodeFromString<Color>(string) == color)
}  
```              

> You can get the full code [here](../guide/example/example-serializer-12.kt).

As before, we got the `Color` class represented as a JSON object with three keys:

```text
{"r":0,"g":255,"b":0}
```                        

<!--- TEST -->    

### Sequential decoding protocol (experimental)

The implementation of the `deserialize` function from the previous section works with any format. However,
some formats either always store all the complex data in order, or only do so sometimes (JSON always stores
collections in order). With these formats the complex protocol of calling `decodeElementIndex` in the loop is 
not needed, and a faster implementation can be used if the [CompositeDecoder.decodeSequentially] function returns `true`.
The plugin-generated serializers are actually conceptually similar to the below code.

<!--- INCLUDE
object ColorAsObjectSerializer : KSerializer<Color> {

    override val descriptor: SerialDescriptor =
        buildClassSerialDescriptor("Color") {
            element<Int>("r")
            element<Int>("g")
            element<Int>("b")
        }

    override fun serialize(encoder: Encoder, value: Color) =
        encoder.encodeStructure(descriptor) {
            encodeIntElement(descriptor, 0, (value.rgb shr 16) and 0xff)
            encodeIntElement(descriptor, 1, (value.rgb shr 8) and 0xff)
            encodeIntElement(descriptor, 2, value.rgb and 0xff)
        }
-->

```kotlin
    override fun deserialize(decoder: Decoder): Color =
        decoder.decodeStructure(descriptor) {
            var r = -1
            var g = -1
            var b = -1     
            if (decodeSequentially()) { // sequential decoding protocol
                r = decodeIntElement(descriptor, 0)           
                g = decodeIntElement(descriptor, 1)  
                b = decodeIntElement(descriptor, 2)
            } else while (true) {
                when (val index = decodeElementIndex(descriptor)) {
                    0 -> r = decodeIntElement(descriptor, 0)
                    1 -> g = decodeIntElement(descriptor, 1)
                    2 -> b = decodeIntElement(descriptor, 2)
                    CompositeDecoder.DECODE_DONE -> break
                    else -> error("Unexpected index: $index")
                }
            }
            require(r in 0..255 && g in 0..255 && b in 0..255)
            Color((r shl 16) or (g shl 8) or b)
        }
```

<!--- INCLUDE
}        

@Serializable(with = ColorAsObjectSerializer::class)
data class Color(val rgb: Int)

fun main() {
    val color = Color(0x00ff00)
    val string = Json.encodeToString(color) 
    println(string)
    require(Json.decodeFromString<Color>(string) == color)
}  
-->

> You can get the full code [here](../guide/example/example-serializer-13.kt).

<!--- TEST
{"r":0,"g":255,"b":0}
--> 

### Serializing 3rd party classes

Sometimes an application has to work with an external type that is not serializable. 
Let us use [java.util.Date] as an example. As before, we start by writing an implementation of [KSerializer]
for the class. Our goal is to get a `Date` serialized as a long number of milliseconds following the 
approach from the [Primitive serializer](#primitive-serializer) section.

> In the following sections any kind of `Date` serializer would work. For example, if we want `Date` to be serialized 
> as an object, we would use an approach from 
> the [Composite serializer via surrogate](#composite-serializer-via-surrogate) section.     
> See also [Deriving external serializer for another Kotlin class (experimental)](#deriving-external-serializer-for-another-kotlin-class-experimental)
> when you need to serialize a 3rd-party Kotlin class that could have been serializable, but is not. 
  
<!--- INCLUDE 
import java.util.Date
import java.text.SimpleDateFormat
-->
  
```kotlin
object DateAsLongSerializer : KSerializer<Date> {
    override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Date", PrimitiveKind.LONG)
    override fun serialize(encoder: Encoder, value: Date) = encoder.encodeLong(value.time)
    override fun deserialize(decoder: Decoder): Date = Date(decoder.decodeLong())
}
```

We cannot bind the `DateAsLongSerializer` serializer to the `Date` class with the [`@Serializable`][Serializable] annotation 
because we don't control the `Date` source code. There are several ways to work around that.

### Passing a serializer manually
 
All `encodeToXxx` and `decodeFromXxx` functions have an overload with the first serializer parameter. 
When a non-serializable class, like `Date`, is the top-level class being serialized we can use those.

```kotlin
fun main() {                                              
    val kotlin10ReleaseDate = SimpleDateFormat("yyyy-MM-ddX").parse("2016-02-15+00") 
    println(Json.encodeToString(DateAsLongSerializer, kotlin10ReleaseDate))    
}
``` 

> You can get the full code [here](../guide/example/example-serializer-14.kt).

```text
1455494400000
```     

<!--- TEST -->

### Specifying serializer on a property

When a property of a non-serializable class, like `Date`, is serialized as part of a serializable class we must supply
its serializer or the code will not compile. This is accomplished using the [`@Serializable`][Serializable] annotation on the property.

<!--- INCLUDE 
import java.util.Date
import java.text.SimpleDateFormat
  
object DateAsLongSerializer : KSerializer<Date> {
    override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Date", PrimitiveKind.LONG)
    override fun serialize(encoder: Encoder, value: Date) = encoder.encodeLong(value.time)
    override fun deserialize(decoder: Decoder): Date = Date(decoder.decodeLong())
}
-->

```kotlin
@Serializable          
class ProgrammingLanguage(
    val name: String,
    @Serializable(with = DateAsLongSerializer::class)
    val stableReleaseDate: Date
)

fun main() {
    val data = ProgrammingLanguage("Kotlin", SimpleDateFormat("yyyy-MM-ddX").parse("2016-02-15+00"))
    println(Json.encodeToString(data))
}
``` 

> You can get the full code [here](../guide/example/example-serializer-15.kt).

The `stableReleaseDate` property is serialized with the serialization strategy that we specified for it:

```text
{"name":"Kotlin","stableReleaseDate":1455494400000}
```    

<!--- TEST -->

### Specifying serializers for a file 

A serializer for a specific type, like `Date`, can be specified for a whole source code file with the file-level
[UseSerializers] annotation at the beginning of the file.

```kotlin
@file:UseSerializers(DateAsLongSerializer::class)
```      

<!--- PREFIX -->

<!--- INCLUDE
import java.util.Date
import java.text.SimpleDateFormat
  
object DateAsLongSerializer : KSerializer<Date> {
    override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Date", PrimitiveKind.LONG)
    override fun serialize(encoder: Encoder, value: Date) = encoder.encodeLong(value.time)
    override fun deserialize(decoder: Decoder): Date = Date(decoder.decodeLong())
}
-->

Now a `Date` property can be used in a serializable class without additional annotations.

```kotlin
@Serializable          
class ProgrammingLanguage(val name: String, val stableReleaseDate: Date)

fun main() {
    val data = ProgrammingLanguage("Kotlin", SimpleDateFormat("yyyy-MM-ddX").parse("2016-02-15+00"))
    println(Json.encodeToString(data))
}
```   
> You can get the full code [here](../guide/example/example-serializer-16.kt).

```text
{"name":"Kotlin","stableReleaseDate":1455494400000}
```

<!--- TEST --> 

### Custom serializers for a generic type

Let us take a look at the following example of the generic `Box<T>` class.
It is marked with `@Serializable(with = BoxSerializer::class)` as we plan to have a custom serialization 
strategy for it.

```kotlin       
@Serializable(with = BoxSerializer::class)
data class Box<T>(val contents: T) 
```                      

An implementation of [KSerializer] for a regular type is written as an `object`, as we saw in this chapter's
examples for the `Color` type. A generic class serializer is instantiated with serializers
for its generic parameters. We saw this in the [Plugin-generated generic serializer](#plugin-generated-generic-serializer) section.
A custom serializer for a generic class must be a `class` with a constructor that accepts as many [KSerializer]
parameters as the type has generic parameters. Let us write a `Box<T>` serializer that erases itself during
serialization, delegating everything to the underlying serializer of its `data` property.

```kotlin
class BoxSerializer<T>(private val dataSerializer: KSerializer<T>) : KSerializer<Box<T>> {
    override val descriptor: SerialDescriptor = dataSerializer.descriptor
    override fun serialize(encoder: Encoder, value: Box<T>) = dataSerializer.serialize(encoder, value.contents)
    override fun deserialize(decoder: Decoder) = Box(dataSerializer.deserialize(decoder))
}
```

Now we can serialize and deserialize `Box<Project>`.

```kotlin
@Serializable
data class Project(val name: String)

fun main() {
    val box = Box(Project("kotlinx.serialization"))
    val string = Json.encodeToString(box)
    println(string)
    println(Json.decodeFromString<Box<Project>>(string))
}
```

> You can get the full code [here](../guide/example/example-serializer-17.kt).

The resulting JSON looks like the `Project` class was serialized directly.

```text
{"name":"kotlinx.serialization"}
Box(contents=Project(name=kotlinx.serialization))
```     

<!--- TEST -->

### Format-specific serializers

The above custom serializers worked in the same way for every format. However, there might be format-specific
features that a serializer implementation would like to take advantage of. 

* The [Json transformations](json.md#json-transformations) section of the [Json](json.md) chapter provides examples
  of serializers that utilize JSON-specific features.
  
* A format implementation can have a format-specific representation for a type as explained
  in the [Format-specific types](formats.md#format-specific-types) section of
  the [Alternative and custom formats (experimental)](formats.md) chapter.  
  
This chapter proceeds with a generic approach to tweaking the serialization strategy based on the context.   

## Contextual serialization

All the previous approaches to specifying custom serialization strategies were _static_, that is 
fully defined at compile-time. The exception was the [Passing a serializer manually](#passing-a-serializer-manually)
approach, but it worked only on a top-level object. You might need to change the serialization
strategy for objects deep in the serialized object tree at run-time, with the strategy being selected in a context-dependent way.
For example, you might want to represent `java.util.Date` in JSON format as an ISO 8601 string or as a long integer
depending on a version of a protocol you are serializing data for. This is called _contextual_ serialization, and it
is supported by a built-in [ContextualSerializer] class. Usually we don't have to use this serializer class explicitly&mdash;there 
is the [Contextual] annotation providing a shortcut to 
the `@Serializable(with = ContextualSerializer::class)` annotation, 
or the [UseContextualSerialization] annotation can be used at the file-level just like 
the [UseSerializers] annotation. Let's see an example utilizing the former.
   
<!--- INCLUDE
import java.util.Date
import java.text.SimpleDateFormat
-->
 
```kotlin
@Serializable          
class ProgrammingLanguage(
    val name: String,
    @Contextual 
    val stableReleaseDate: Date
)
```

<!--- INCLUDE

fun main() {
    val data = ProgrammingLanguage("Kotlin", SimpleDateFormat("yyyy-MM-ddX").parse("2016-02-15+00"))
    println(Json.encodeToString(data))
}
-->    

To actually serialize this class we must provide the corresponding context when calling the `encodeToXxx`/`decodeFromXxx`
functions. Without it we'll get a "Serializer for class 'Date' is not found" exception.

> See [here](../guide/example/example-serializer-18.kt) for an example that produces that exception.
 
<!--- TEST LINES_START 
Exception in thread "main" kotlinx.serialization.SerializationException: Serializer for class 'Date' is not found.
Mark the class as @Serializable or provide the serializer explicitly.
-->

<!--- INCLUDE
import kotlinx.serialization.modules.*
import java.util.Date
import java.text.SimpleDateFormat
  
object DateAsLongSerializer : KSerializer<Date> {
    override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Date", PrimitiveKind.LONG)
    override fun serialize(encoder: Encoder, value: Date) = encoder.encodeLong(value.time)
    override fun deserialize(decoder: Decoder): Date = Date(decoder.decodeLong())
}

@Serializable          
class ProgrammingLanguage(
    val name: String,
    @Contextual 
    val stableReleaseDate: Date
)
-->

### Serializers module

To provide a context, we define a [SerializersModule] instance that describes which serializers shall be used 
at run-time to serialize which contextually-serializable classes. This is done using the 
[SerializersModule {}][SerializersModule()] builder function, which provides the [SerializersModuleBuilder] DSL to 
register serializers. In the below example we use the [contextual][_contextual] function with the serializer. The corresponding
class this serializer is defined for is fetched automatically via the `reified` type parameter.  

```kotlin
private val module = SerializersModule { 
    contextual(DateAsLongSerializer)
}
```

Next we create an instance of the [Json] format with this module using the 
[Json {}][Json()] builder function and the [serializersModule][JsonBuilder.serializersModule] property. 

> Details on custom JSON configurations can be found in 
> the [JSON configuration](json.md#json-configuration) section. 

```kotlin           
val format = Json { serializersModule = module }
```

Now we can serialize our data with this `format`.

```kotlin
fun main() {
    val data = ProgrammingLanguage("Kotlin", SimpleDateFormat("yyyy-MM-ddX").parse("2016-02-15+00"))
    println(format.encodeToString(data))
}
```

> You can get the full code [here](../guide/example/example-serializer-19.kt).
```text
{"name":"Kotlin","stableReleaseDate":1455494400000}
```

<!--- TEST -->

### Contextual serialization and generic classes

In the previous section we saw that we can register serializer instance in the module for a class we want to serialize contextually. 
We also know that [serializers for generic classes have constructor parameters](#custom-serializers-for-a-generic-type) — type arguments serializers. 
It means that we can't use one serializer instance for a class if this class is generic:

```kotlin
val incorrectModule = SerializersModule {
    // Can serialize only Box<Int>, but not Box<String> or others
    contextual(BoxSerializer(Int.serializer()))
}
```

For cases when one want to serialize contextually a generic class, it is possible to register provider in the module:

```kotlin
val correctModule = SerializersModule {
    // args[0] contains Int.serializer() or String.serializer(), depending on the usage
    contextual(Box::class) { args -> BoxSerializer(args[0]) } 
}
```

<!--- CLEAR -->

> Additional details on serialization modules are given in 
> the [Merging library serializers modules](polymorphism.md#merging-library-serializers-modules) section of
> the [Polymorphism](polymorphism.md) chapter.

## Deriving external serializer for another Kotlin class (experimental)

If a 3rd-party class to be serialized is a Kotlin class with a properties-only primary constructor, a kind of
class which could have been made `@Serializable`, then you can generate an _external_ serializer for it
using the [Serializer] annotation on an object with the [`forClass`][Serializer.forClass] property. 

```kotlin         
// NOT @Serializable
class Project(val name: String, val language: String)
                           
@Serializer(forClass = Project::class)
object ProjectSerializer
```

You must bind this serializer to a class using one of the approaches explained in this chapter. We'll
follow the [Passing a serializer manually](#passing-a-serializer-manually) approach for this example.

```kotlin 
fun main() {
    val data = Project("kotlinx.serialization", "Kotlin")
    println(Json.encodeToString(ProjectSerializer, data))    
}
```          

> You can get the full code [here](../guide/example/example-serializer-20.kt).

This gets all the `Project` properties serialized:

```text
{"name":"kotlinx.serialization","language":"Kotlin"}
```     

<!--- TEST -->

### External serialization uses properties 

As we saw earlier, the regular `@Serializable` annotation creates a serializer so that 
[Backing fields are serialized](basic-serialization.md#backing-fields-are-serialized). _External_ serialization using 
`Serializer(forClass = ...)` has no access to backing fields and works differently. 
It serializes only _accessible_ properties that have setters or are part of the primary constructor. 
The following example shows this.

```kotlin        
// NOT @Serializable, will use external serializer
class Project(
    // val in a primary constructor -- serialized
    val name: String
) {
    var stars: Int = 0 // property with getter & setter -- serialized
 
    val path: String // getter only -- not serialized
        get() = "kotlin/$name"                                         

    private var locked: Boolean = false // private, not accessible -- not serialized 
}              

@Serializer(forClass = Project::class)
object ProjectSerializer

fun main() {
    val data = Project("kotlinx.serialization").apply { stars = 9000 }
    println(Json.encodeToString(ProjectSerializer, data))
}
```             

> You can get the full code [here](../guide/example/example-serializer-21.kt).

The output is shown below.

```text
{"name":"kotlinx.serialization","stars":9000}
```     

<!--- TEST -->

---

The next chapter covers [Polymorphism](polymorphism.md).

<!-- Java references -->
[java.util.Date]: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html

<!--- MODULE /kotlinx-serialization-core -->
<!--- INDEX kotlinx-serialization-core/kotlinx.serialization -->

[Serializable]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization/-serializable/index.html
[KSerializer]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization/-k-serializer/index.html
[KSerializer.descriptor]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization/-k-serializer/descriptor.html
[SerializationStrategy.serialize]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization/-serialization-strategy/serialize.html
[SerializationStrategy]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization/-serialization-strategy/index.html
[DeserializationStrategy.deserialize]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization/-deserialization-strategy/deserialize.html
[DeserializationStrategy]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization/-deserialization-strategy/index.html
[Serializable.with]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization/-serializable/with.html
[SerialName]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization/-serial-name/index.html
[UseSerializers]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization/-use-serializers/index.html
[ContextualSerializer]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization/-contextual-serializer/index.html
[Contextual]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization/-contextual/index.html
[UseContextualSerialization]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization/-use-contextual-serialization/index.html
[Serializer]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization/-serializer/index.html
[Serializer.forClass]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization/-serializer/for-class.html

<!--- INDEX kotlinx-serialization-core/kotlinx.serialization.builtins -->

[ListSerializer()]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.builtins/-list-serializer.html
[SetSerializer()]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.builtins/-set-serializer.html
[MapSerializer()]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.builtins/-map-serializer.html

<!--- INDEX kotlinx-serialization-core/kotlinx.serialization.encoding -->

[Encoder]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.encoding/-encoder/index.html
[Encoder.encodeString]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.encoding/-encoder/encode-string.html
[Decoder]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.encoding/-decoder/index.html
[Decoder.decodeString]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.encoding/-decoder/decode-string.html
[Encoder.encodeSerializableValue]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.encoding/-encoder/encode-serializable-value.html
[Decoder.decodeSerializableValue]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.encoding/-decoder/decode-serializable-value.html
[encodeStructure]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.encoding/encode-structure.html
[CompositeEncoder]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.encoding/-composite-encoder/index.html
[decodeStructure]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.encoding/decode-structure.html
[CompositeDecoder]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.encoding/-composite-decoder/index.html
[CompositeDecoder.decodeElementIndex]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.encoding/-composite-decoder/decode-element-index.html
[CompositeDecoder.decodeIntElement]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.encoding/-composite-decoder/decode-int-element.html
[CompositeDecoder.decodeSequentially]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.encoding/-composite-decoder/decode-sequentially.html

<!--- INDEX kotlinx-serialization-core/kotlinx.serialization.descriptors -->

[PrimitiveSerialDescriptor()]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.descriptors/-primitive-serial-descriptor.html
[PrimitiveKind]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.descriptors/-primitive-kind/index.html
[SerialDescriptor]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.descriptors/-serial-descriptor/index.html
[buildClassSerialDescriptor]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.descriptors/build-class-serial-descriptor.html
[ClassSerialDescriptorBuilder.element]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.descriptors/element.html
[SerialKind]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.descriptors/-serial-kind/index.html

<!--- INDEX kotlinx-serialization-core/kotlinx.serialization.modules -->

[SerializersModule]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.modules/-serializers-module/index.html
[SerializersModule()]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.modules/-serializers-module.html
[SerializersModuleBuilder]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.modules/-serializers-module-builder/index.html
[_contextual]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.modules/contextual.html

<!--- MODULE /kotlinx-serialization-json -->
<!--- INDEX kotlinx-serialization-json/kotlinx.serialization.json -->

[Json]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json/index.html
[Json()]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json.html
[JsonBuilder.serializersModule]: https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-builder/serializers-module.html

<!--- END -->