@@ -33,10 +33,10 @@ This chapter shows the basic use of Kotlin Serialization and explains its core c
33
33
## Basics
34
34
35
35
To convert an object tree to a string or to a sequence of bytes, it must come
36
- through two mutually intertwined processes. In the first step, an object is _ serialized_ &mdash ;
37
- it is converted into a serial sequence of its constituting primitive values. This process is common for all
36
+ through two mutually intertwined processes. In the first step, an object is _ serialized_ &mdash ; it
37
+ is converted into a serial sequence of its constituting primitive values. This process is common for all
38
38
data formats and its result depends on the object being serialized. A _ serializer_ controls this process.
39
- The second step is called _ encoding_ &mdash ; it is the conversion of the corresponding sequence of primitives into
39
+ The second step is called _ encoding_ &mdash ; it is the conversion of the corresponding sequence of primitives into
40
40
the output format representation. An _ encoder_ controls this process. Whenever the distinction is not important,
41
41
both the terms of encoding and serialization are used interchangeably.
42
42
@@ -58,10 +58,9 @@ import kotlinx.serialization.json.*
58
58
59
59
### JSON encoding
60
60
61
- The whole process of converting data into a specific format is called _ encoding_ . For JSON we
62
- encode data using the [ Json.encodeToString] [ kotlinx.serialization.encodeToString ] extension function.
63
- It serializes the object
64
- that is passed as its parameter under the hood and encodes it to a JSON string.
61
+ The whole process of converting data into a specific format is called _ encoding_ . For JSON we encode data
62
+ using the [ Json.encodeToString] [ kotlinx.serialization.encodeToString ] extension function. It serializes
63
+ the object that is passed as its parameter under the hood and encodes it to a JSON string.
65
64
66
65
Let's start with a class describing a project and try to get its JSON representation.
67
66
@@ -85,7 +84,7 @@ Mark the class as @Serializable or provide the serializer explicitly.
85
84
86
85
<!-- - TEST LINES_START -->
87
86
88
- Serializable classes have to be explicitly marked. Kotlin serialization does not use reflection,
87
+ Serializable classes have to be explicitly marked. Kotlin Serialization does not use reflection,
89
88
so you cannot accidentally deserialize a class which was not supposed to be serializable. We fix it by
90
89
adding the [ ` @Serializable ` ] [ Serializable ] annotation.
91
90
@@ -101,7 +100,7 @@ fun main() {
101
100
102
101
> You can get the full code [ here] ( ../guide/example/example-basic-02.kt ) .
103
102
104
- The ` @Serializable ` annotation instructs Kotlin Serialization plugin to automatically generate and hook
103
+ The ` @Serializable ` annotation instructs the Kotlin Serialization plugin to automatically generate and hook
105
104
up a _ serializer_ for this class. Now the output of the example is the corresponding JSON.
106
105
107
106
``` text
@@ -111,17 +110,16 @@ up a _serializer_ for this class. Now the output of the example is the correspon
111
110
<!-- - TEST -->
112
111
113
112
> There is a whole chapter about the [ Serializers] ( serializers.md ) . For now, it is enough to know
114
- > that they are automatically generated by the Kotlin serialization plugin.
113
+ > that they are automatically generated by the Kotlin Serialization plugin.
115
114
116
115
### JSON decoding
117
116
118
117
The reverse process is called _ decoding_ . To decode a JSON string into an object, we'll
119
118
use the [ Json.decodeFromString] [ kotlinx.serialization.decodeFromString ] extension function.
120
- To specify which type we want to get as a result,
121
- we provide a type parameter to this function.
119
+ To specify which type we want to get as a result, we provide a type parameter to this function.
122
120
123
121
As we'll see later, serialization works with different kinds of classes.
124
- Here we are marking our ` Project ` class as ` data class ` not because it is required, but because
122
+ Here we are marking our ` Project ` class as a ` data class ` , not because it is required, but because
125
123
we want to print its contents to verify how it decodes.
126
124
127
125
``` kotlin
@@ -157,7 +155,7 @@ import kotlinx.serialization.json.*
157
155
158
156
### Backing fields are serialized
159
157
160
- Only class's properties with backing fields are serialized, so properties with getter/setter that don't
158
+ Only a class's properties with backing fields are serialized, so properties with a getter/setter that don't
161
159
have a backing field and delegated properties are not serialized, as the following example shows.
162
160
163
161
``` kotlin
@@ -182,7 +180,7 @@ fun main() {
182
180
183
181
> You can get the full code [ here] ( ../guide/example/example-classes-01.kt ) .
184
182
185
- We can clearly see that only ` name ` and ` stars ` properties are present in the JSON output.
183
+ We can clearly see that only the ` name ` and ` stars ` properties are present in the JSON output.
186
184
187
185
``` text
188
186
{"name":"kotlinx.serialization","stars":9000}
@@ -192,8 +190,8 @@ We can clearly see that only `name` and `stars` properties are present in the JS
192
190
193
191
### Constructor properties requirement
194
192
195
- If we want to define the ` Project ` class so that it takes a path string and then
196
- deconstructs them into the corresponding properties, then we might be tempted to write something like the code below.
193
+ If we want to define the ` Project ` class so that it takes a path string, and then
194
+ deconstructs it into the corresponding properties, we might be tempted to write something like the code below.
197
195
198
196
``` kotlin
199
197
@Serializable
@@ -205,9 +203,9 @@ class Project(path: String) {
205
203
206
204
<!-- - CLEAR -->
207
205
208
- This class does not compile, because ` @Serializable ` annotation requires that all parameters of the class primary
209
- constructor are properties. A simple workaround is to define a private primary constructor with class's
210
- properties and turn the constructor we wanted into the secondary one.
206
+ This class does not compile because the ` @Serializable ` annotation requires that all parameters of the class's primary
207
+ constructor be properties. A simple workaround is to define a private primary constructor with the class's
208
+ properties, and turn the constructor we wanted into the secondary one.
211
209
212
210
``` kotlin
213
211
@Serializable
@@ -222,7 +220,7 @@ class Project private constructor(val owner: String, val name: String) {
222
220
}
223
221
```
224
222
225
- Serialization works with private primary constructor and still serializes only backing fields.
223
+ Serialization works with a private primary constructor, and still serializes only backing fields.
226
224
227
225
``` kotlin
228
226
fun main () {
@@ -244,7 +242,7 @@ This example produces the expected output.
244
242
245
243
Another case where you might want to introduce a primary constructor parameter without a property is when you
246
244
want to validate its value before storing it to a property. To make it serializable you shall replace it
247
- with a property in the primary constructor and move validation to an ` init { ... } ` block.
245
+ with a property in the primary constructor, and move the validation to an ` init { ... } ` block.
248
246
249
247
``` kotlin
250
248
@Serializable
@@ -269,7 +267,7 @@ fun main() {
269
267
270
268
> You can get the full code [ here] ( ../guide/example/example-classes-03.kt ) .
271
269
272
- Running this code produces the exception.
270
+ Running this code produces the exception:
273
271
274
272
``` text
275
273
Exception in thread "main" java.lang.IllegalArgumentException: name cannot be empty
@@ -296,7 +294,7 @@ fun main() {
296
294
297
295
> You can get the full code [ here] ( ../guide/example/example-classes-04.kt ) .
298
296
299
- It produces the exception.
297
+ It produces the exception:
300
298
301
299
``` text
302
300
Exception in thread "main" kotlinx.serialization.MissingFieldException: Field 'language' is required, but it was missing
@@ -305,7 +303,7 @@ Exception in thread "main" kotlinx.serialization.MissingFieldException: Field 'l
305
303
<!-- - TEST LINES_START -->
306
304
307
305
This problem can be fixed by adding a default value to the property, which automatically makes it optional
308
- for serialization:
306
+ for serialization.
309
307
310
308
``` kotlin
311
309
@Serializable
@@ -354,7 +352,7 @@ fun main() {
354
352
355
353
> You can get the full code [ here] ( ../guide/example/example-classes-06.kt ) .
356
354
357
- Since ` language ` property was specified in the input, we don't see "Computing" string printed
355
+ Since the ` language ` property was specified in the input, we don't see the "Computing" string printed
358
356
in the output.
359
357
360
358
``` text
@@ -366,7 +364,7 @@ Project(name=kotlinx.serialization, language=Kotlin)
366
364
### Required properties
367
365
368
366
A property with a default value can be required in a serial format with the [ ` @Required ` ] [ Required ] annotation.
369
- Let us change the previous example by marking ` language ` property as ` @Required ` .
367
+ Let us change the previous example by marking the ` language ` property as ` @Required ` .
370
368
371
369
``` kotlin
372
370
@Serializable
@@ -419,12 +417,12 @@ Use 'ignoreUnknownKeys = true' in 'Json {}' builder to ignore unknown keys.
419
417
420
418
<!-- - TEST LINES_START -->
421
419
422
- > 'ignoreUnknownKeys' feature is explained in the [ Ignoring Unknown Keys section] ( json.md#ignoring-unknown-keys ) section.
420
+ > The 'ignoreUnknownKeys' feature is explained in the [ Ignoring Unknown Keys section] ( json.md#ignoring-unknown-keys ) section.
423
421
424
422
### Defaults are not encoded
425
423
426
- Default values are not encoded by default in JSON. This behavior is motivated by the fact that in most real-life scenarios,
427
- such configuration reduces visual clutter and saves amount of data being serialized.
424
+ Default values are not encoded by default in JSON. This behavior is motivated by the fact that in most real-life scenarios
425
+ such configuration reduces visual clutter, and saves the amount of data being serialized.
428
426
429
427
``` kotlin
430
428
@Serializable
@@ -438,7 +436,7 @@ fun main() {
438
436
439
437
> You can get the full code [ here] ( ../guide/example/example-classes-09.kt ) .
440
438
441
- It produces the following output, which does not have ` language ` property, because its value is equal to the default one.
439
+ It produces the following output, which does not have the ` language ` property because its value is equal to the default one.
442
440
443
441
``` text
444
442
{"name":"kotlinx.serialization"}
@@ -450,7 +448,7 @@ It produces the following output, which does not have `language` property, becau
450
448
451
449
### Nullable properties
452
450
453
- Nullable properties are natively supported by Kotlin serialization .
451
+ Nullable properties are natively supported by Kotlin Serialization .
454
452
455
453
``` kotlin
456
454
@Serializable
@@ -474,7 +472,7 @@ This example does not encode `null` in JSON because [Defaults are not encoded](#
474
472
475
473
### Type safety is enforced
476
474
477
- Kotlin serialization strongly enforces type safety of the Kotlin programming language.
475
+ Kotlin Serialization strongly enforces the type safety of the Kotlin programming language.
478
476
In particular, let us try to decode a ` null ` value from a JSON object into a non-nullable Kotlin property ` language ` .
479
477
480
478
``` kotlin
@@ -531,14 +529,14 @@ When encoded to JSON it results in a nested JSON object.
531
529
{"name":"kotlinx.serialization","owner":{"name":"kotlin"}}
532
530
```
533
531
534
- > References to non-serializable classes can be marked as [ Transient properties] ( #transient-properties ) or a
532
+ > References to non-serializable classes can be marked as [ Transient properties] ( #transient-properties ) , or a
535
533
> custom serializer can be provided for them as shown in the [ Serializers] ( serializers.md ) chapter.
536
534
537
535
<!-- - TEST -->
538
536
539
537
### No compression of repeated references
540
538
541
- Kotlin serialization is designed for encoding and decoding of plain data. It does not support reconstruction
539
+ Kotlin Serialization is designed for encoding and decoding of plain data. It does not support reconstruction
542
540
of arbitrary object graphs with repeated object references. For example, let us try to serialize an object
543
541
that references the same ` owner ` instance twice.
544
542
@@ -564,22 +562,22 @@ We simply get the `owner` value encoded twice.
564
562
{"name":"kotlinx.serialization","owner":{"name":"kotlin"},"maintainer":{"name":"kotlin"}}
565
563
```
566
564
567
- > Attempt to serialize a circular structure will end up with stack overflow.
565
+ > Attempt to serialize a circular structure will result in stack overflow.
568
566
> You can use the [ Transient properties] ( #transient-properties ) to exclude some references from serialization.
569
567
570
568
<!-- - TEST -->
571
569
572
570
### Generic classes
573
571
574
- Generic classes in Kotlin provide type-polymorphic behavior, which is enforced by Kotlin serialization at
572
+ Generic classes in Kotlin provide type-polymorphic behavior, which is enforced by Kotlin Serialization at
575
573
compile-time. For example, consider a generic serializable class ` Box<T> ` .
576
574
577
575
``` kotlin
578
576
@Serializable
579
577
class Box <T >(val contents : T )
580
578
```
581
579
582
- The ` Box<T> ` class can be used with builtin types like ` Int ` as well as with user-defined types like ` Project ` .
580
+ The ` Box<T> ` class can be used with builtin types like ` Int ` , as well as with user-defined types like ` Project ` .
583
581
584
582
<!-- - INCLUDE
585
583
@@ -610,14 +608,14 @@ The actual type that we get in JSON depends on the actual compile-time type para
610
608
611
609
<!-- - TEST -->
612
610
613
- If the actual generic type is not serializable, compile-time error will be produced.
611
+ If the actual generic type is not serializable a compile-time error will be produced.
614
612
615
613
### Serial field names
616
614
617
615
The names of the properties used in encoded representation, JSON in our examples, are the same as
618
- their names in the source code by default. The name that is used for serialization is called a _ serial name_ and
619
- can be changed using the [ ` @SerialName ` ] [ SerialName ] annotation. For example, we can have a ` language ` property in the source,
620
- with an abbreviated serial name.
616
+ their names in the source code by default. The name that is used for serialization is called a _ serial name_ , and
617
+ can be changed using the [ ` @SerialName ` ] [ SerialName ] annotation. For example, we can have a ` language ` property in
618
+ the source with an abbreviated serial name.
621
619
622
620
``` kotlin
623
621
@Serializable
@@ -657,4 +655,3 @@ The next chapter covers [Builtin classes](builtin-classes.md).
657
655
<!-- - MODULE /kotlinx-serialization-json -->
658
656
<!-- - INDEX kotlinx-serialization-json/kotlinx.serialization.json -->
659
657
<!-- - END -->
660
-
0 commit comments