0
# Configuration
1
2
Comprehensive configuration system for customizing JSON serialization behavior, formatting options, and parsing rules through the JsonBuilder and JsonConfiguration classes.
3
4
## Capabilities
5
6
### JsonBuilder - Configuration Builder
7
8
Mutable builder for creating Json instances with custom configuration options.
9
10
```kotlin { .api }
11
/**
12
* Builder for creating Json instances with custom configuration
13
*/
14
class JsonBuilder {
15
/**
16
* Whether to encode properties with default values
17
* Default: false
18
*/
19
var encodeDefaults: Boolean
20
21
/**
22
* Whether to encode explicit null values
23
* Default: true
24
*/
25
var explicitNulls: Boolean
26
27
/**
28
* Whether to ignore unknown JSON properties during deserialization
29
* Default: false
30
*/
31
var ignoreUnknownKeys: Boolean
32
33
/**
34
* Whether to use relaxed parsing mode allowing unquoted keys and values
35
* Default: false
36
*/
37
var isLenient: Boolean
38
39
/**
40
* Whether to format output JSON with indentation and line breaks
41
* Default: false
42
*/
43
var prettyPrint: Boolean
44
45
/**
46
* Custom indentation string for pretty printing
47
* Default: " " (4 spaces)
48
*/
49
@ExperimentalSerializationApi
50
var prettyPrintIndent: String
51
52
/**
53
* Whether to coerce incorrect input types during deserialization
54
* Default: false
55
*/
56
var coerceInputValues: Boolean
57
58
/**
59
* Property name for polymorphic type discriminator
60
* Default: "type"
61
*/
62
var classDiscriminator: String
63
64
/**
65
* Mode controlling when class discriminator is included
66
* Default: ClassDiscriminatorMode.POLYMORPHIC
67
*/
68
@ExperimentalSerializationApi
69
var classDiscriminatorMode: ClassDiscriminatorMode
70
71
/**
72
* Whether to allow special floating point values (NaN, Infinity)
73
* Default: false
74
*/
75
var allowSpecialFloatingPointValues: Boolean
76
77
/**
78
* Whether to allow non-primitive map keys (serialized as arrays)
79
* Default: false
80
*/
81
var allowStructuredMapKeys: Boolean
82
83
/**
84
* Whether to use array format for polymorphic serialization
85
* Default: false
86
*/
87
var useArrayPolymorphism: Boolean
88
89
/**
90
* Whether to use alternative names specified by @JsonNames
91
* Default: true
92
*/
93
var useAlternativeNames: Boolean
94
95
/**
96
* Strategy for transforming property names during serialization
97
* Default: null (no transformation)
98
*/
99
@ExperimentalSerializationApi
100
var namingStrategy: JsonNamingStrategy?
101
102
/**
103
* Whether to decode enum values case-insensitively
104
* Default: false
105
*/
106
@ExperimentalSerializationApi
107
var decodeEnumsCaseInsensitive: Boolean
108
109
/**
110
* Whether to allow trailing commas in objects and arrays
111
* Default: false
112
*/
113
@ExperimentalSerializationApi
114
var allowTrailingComma: Boolean
115
116
/**
117
* Whether to allow C/C++ style comments in JSON
118
* Default: false
119
*/
120
@ExperimentalSerializationApi
121
var allowComments: Boolean
122
123
/**
124
* Module containing custom serializers for types
125
* Default: EmptySerializersModule
126
*/
127
var serializersModule: SerializersModule
128
}
129
```
130
131
### JsonConfiguration - Immutable Configuration
132
133
Immutable configuration instance containing all JSON processing settings.
134
135
```kotlin { .api }
136
/**
137
* Immutable configuration for Json instances
138
* Contains all serialization and deserialization settings
139
*/
140
class JsonConfiguration {
141
val encodeDefaults: Boolean
142
val explicitNulls: Boolean
143
val ignoreUnknownKeys: Boolean
144
val isLenient: Boolean
145
val prettyPrint: Boolean
146
val coerceInputValues: Boolean
147
val classDiscriminator: String
148
val allowSpecialFloatingPointValues: Boolean
149
val allowStructuredMapKeys: Boolean
150
val useArrayPolymorphism: Boolean
151
val useAlternativeNames: Boolean
152
// Additional configuration properties...
153
}
154
```
155
156
### Configuration Examples
157
158
**Basic Configuration:**
159
160
```kotlin
161
import kotlinx.serialization.json.*
162
163
// Simple configuration
164
val json = Json {
165
prettyPrint = true
166
ignoreUnknownKeys = true
167
}
168
169
// Lenient parsing for relaxed JSON
170
val lenientJson = Json {
171
isLenient = true
172
coerceInputValues = true
173
ignoreUnknownKeys = true
174
}
175
176
// Production configuration
177
val productionJson = Json {
178
encodeDefaults = false
179
explicitNulls = false
180
ignoreUnknownKeys = true
181
coerceInputValues = true
182
}
183
```
184
185
## Configuration Options
186
187
### Encoding Behavior
188
189
Control how Kotlin objects are serialized to JSON.
190
191
```kotlin { .api }
192
var encodeDefaults: Boolean
193
var explicitNulls: Boolean
194
var prettyPrint: Boolean
195
@ExperimentalSerializationApi
196
var prettyPrintIndent: String
197
```
198
199
**Usage Examples:**
200
201
```kotlin
202
import kotlinx.serialization.*
203
import kotlinx.serialization.json.*
204
205
@Serializable
206
data class User(
207
val name: String,
208
val age: Int = 25,
209
val email: String? = null,
210
val active: Boolean = true
211
)
212
213
val user = User("Alice", email = "alice@example.com")
214
215
// Default encoding (no defaults, explicit nulls)
216
val defaultJson = Json
217
val default = defaultJson.encodeToString(user)
218
// Result: {"name":"Alice","email":"alice@example.com"}
219
220
// Encode defaults and explicit nulls
221
val verboseJson = Json {
222
encodeDefaults = true
223
explicitNulls = true
224
}
225
val verbose = verboseJson.encodeToString(user)
226
// Result: {"name":"Alice","age":25,"email":"alice@example.com","active":true}
227
228
// Pretty printing
229
val prettyJson = Json {
230
prettyPrint = true
231
encodeDefaults = true
232
}
233
val pretty = prettyJson.encodeToString(user)
234
// Result:
235
// {
236
// "name": "Alice",
237
// "age": 25,
238
// "email": "alice@example.com",
239
// "active": true
240
// }
241
242
// Custom indentation (experimental)
243
val customIndentJson = Json {
244
prettyPrint = true
245
prettyPrintIndent = " " // 2 spaces instead of 4
246
}
247
```
248
249
### Decoding Behavior
250
251
Control how JSON is parsed and deserialized to Kotlin objects.
252
253
```kotlin { .api }
254
var ignoreUnknownKeys: Boolean
255
var isLenient: Boolean
256
var coerceInputValues: Boolean
257
@ExperimentalSerializationApi
258
var decodeEnumsCaseInsensitive: Boolean
259
@ExperimentalSerializationApi
260
var allowTrailingComma: Boolean
261
@ExperimentalSerializationApi
262
var allowComments: Boolean
263
```
264
265
**Usage Examples:**
266
267
```kotlin
268
import kotlinx.serialization.*
269
import kotlinx.serialization.json.*
270
271
@Serializable
272
data class Config(val timeout: Int, val enabled: Boolean)
273
274
// Strict parsing (default)
275
val strictJson = Json
276
try {
277
val config = strictJson.decodeFromString<Config>("""
278
{
279
"timeout": 30,
280
"enabled": true,
281
"extra": "ignored" // This will cause an error
282
}
283
""")
284
} catch (e: Exception) {
285
// SerializationException: Encountered unknown key 'extra'
286
}
287
288
// Ignore unknown keys
289
val flexibleJson = Json {
290
ignoreUnknownKeys = true
291
}
292
val config1 = flexibleJson.decodeFromString<Config>("""
293
{
294
"timeout": 30,
295
"enabled": true,
296
"extra": "ignored" // This is now ignored
297
}
298
""")
299
300
// Lenient parsing allows unquoted keys and values
301
val lenientJson = Json {
302
isLenient = true
303
}
304
val config2 = lenientJson.decodeFromString<Config>("""
305
{
306
timeout: 30, // Unquoted key
307
enabled: true
308
}
309
""")
310
311
// Coerce input values
312
val coercingJson = Json {
313
coerceInputValues = true
314
}
315
val config3 = coercingJson.decodeFromString<Config>("""
316
{
317
"timeout": "30", // String coerced to Int
318
"enabled": 1 // Number coerced to Boolean
319
}
320
""")
321
322
// Allow trailing commas and comments (experimental)
323
val relaxedJson = Json {
324
allowTrailingComma = true
325
allowComments = true
326
}
327
val config4 = relaxedJson.decodeFromString<Config>("""
328
{
329
// Configuration settings
330
"timeout": 30,
331
"enabled": true, // Trailing comma allowed
332
}
333
""")
334
```
335
336
### Polymorphic Serialization Configuration
337
338
Control how polymorphic types are serialized and deserialized.
339
340
```kotlin { .api }
341
var classDiscriminator: String
342
@ExperimentalSerializationApi
343
var classDiscriminatorMode: ClassDiscriminatorMode
344
var useArrayPolymorphism: Boolean
345
346
enum class ClassDiscriminatorMode {
347
NONE, ALL_JSON_OBJECTS, POLYMORPHIC
348
}
349
```
350
351
**Usage Examples:**
352
353
```kotlin
354
import kotlinx.serialization.*
355
import kotlinx.serialization.json.*
356
357
@Serializable
358
sealed class Shape {
359
abstract val area: Double
360
}
361
362
@Serializable
363
@SerialName("circle")
364
data class Circle(val radius: Double) : Shape() {
365
override val area: Double get() = 3.14159 * radius * radius
366
}
367
368
@Serializable
369
@SerialName("rectangle")
370
data class Rectangle(val width: Double, val height: Double) : Shape() {
371
override val area: Double get() = width * height
372
}
373
374
val shapes = listOf<Shape>(
375
Circle(5.0),
376
Rectangle(4.0, 3.0)
377
)
378
379
// Default polymorphic serialization
380
val defaultJson = Json {
381
classDiscriminator = "type"
382
}
383
val default = defaultJson.encodeToString(shapes)
384
// Result: [{"type":"circle","radius":5.0},{"type":"rectangle","width":4.0,"height":3.0}]
385
386
// Custom discriminator name
387
val customJson = Json {
388
classDiscriminator = "kind"
389
}
390
val custom = customJson.encodeToString(shapes)
391
// Result: [{"kind":"circle","radius":5.0},{"kind":"rectangle","width":4.0,"height":3.0}]
392
393
// Array polymorphism
394
val arrayJson = Json {
395
useArrayPolymorphism = true
396
}
397
val array = arrayJson.encodeToString(shapes)
398
// Result: [["circle",{"radius":5.0}],["rectangle",{"width":4.0,"height":3.0}]]
399
400
// Control discriminator inclusion mode (experimental)
401
val allObjectsJson = Json {
402
classDiscriminatorMode = ClassDiscriminatorMode.ALL_JSON_OBJECTS
403
}
404
```
405
406
### Special Value Handling
407
408
Configure handling of special floating-point values and complex map keys.
409
410
```kotlin { .api }
411
var allowSpecialFloatingPointValues: Boolean
412
var allowStructuredMapKeys: Boolean
413
```
414
415
**Usage Examples:**
416
417
```kotlin
418
import kotlinx.serialization.*
419
import kotlinx.serialization.json.*
420
421
@Serializable
422
data class FloatData(val value: Double, val ratio: Float)
423
424
@Serializable
425
data class ComplexKey(val x: Int, val y: Int)
426
427
// Special floating point values
428
val specialJson = Json {
429
allowSpecialFloatingPointValues = true
430
}
431
val floatData = FloatData(Double.NaN, Float.POSITIVE_INFINITY)
432
val encoded = specialJson.encodeToString(floatData)
433
// Result: {"value":NaN,"ratio":Infinity}
434
435
// Structured map keys
436
val structuredJson = Json {
437
allowStructuredMapKeys = true
438
}
439
val complexMap = mapOf(
440
ComplexKey(1, 2) to "point1",
441
ComplexKey(3, 4) to "point2"
442
)
443
val mapEncoded = structuredJson.encodeToString(complexMap)
444
// Result: [["{"x":1,"y":2}","point1"],["{"x":3,"y":4}","point2"]]
445
```
446
447
### Naming Strategy Configuration
448
449
Configure property name transformation during serialization.
450
451
```kotlin { .api }
452
@ExperimentalSerializationApi
453
var namingStrategy: JsonNamingStrategy?
454
var useAlternativeNames: Boolean
455
456
fun interface JsonNamingStrategy {
457
fun serialNameForJson(descriptor: SerialDescriptor, elementIndex: Int, serialName: String): String
458
459
companion object {
460
val SnakeCase: JsonNamingStrategy
461
val KebabCase: JsonNamingStrategy
462
}
463
}
464
```
465
466
**Usage Examples:**
467
468
```kotlin
469
import kotlinx.serialization.*
470
import kotlinx.serialization.json.*
471
472
@Serializable
473
data class UserProfile(
474
val firstName: String,
475
val lastName: String,
476
val emailAddress: String,
477
val phoneNumber: String?
478
)
479
480
val user = UserProfile("John", "Doe", "john@example.com", "555-1234")
481
482
// Snake case naming
483
val snakeCaseJson = Json {
484
namingStrategy = JsonNamingStrategy.SnakeCase
485
}
486
val snakeCase = snakeCaseJson.encodeToString(user)
487
// Result: {"first_name":"John","last_name":"Doe","email_address":"john@example.com","phone_number":"555-1234"}
488
489
// Kebab case naming
490
val kebabCaseJson = Json {
491
namingStrategy = JsonNamingStrategy.KebabCase
492
}
493
val kebabCase = kebabCaseJson.encodeToString(user)
494
// Result: {"first-name":"John","last-name":"Doe","email-address":"john@example.com","phone-number":"555-1234"}
495
496
// Alternative names with @JsonNames
497
@Serializable
498
data class ApiResponse(
499
@JsonNames("user_id", "userId")
500
val id: Int,
501
val message: String
502
)
503
504
val alternativeJson = Json {
505
useAlternativeNames = true
506
}
507
// Can decode from any of: "id", "user_id", or "userId"
508
val response1 = alternativeJson.decodeFromString<ApiResponse>("""{"user_id":123,"message":"success"}""")
509
val response2 = alternativeJson.decodeFromString<ApiResponse>("""{"userId":123,"message":"success"}""")
510
```
511
512
### Serializers Module Configuration
513
514
Configure custom serializers and type handling.
515
516
```kotlin { .api }
517
var serializersModule: SerializersModule
518
```
519
520
**Usage Examples:**
521
522
```kotlin
523
import kotlinx.serialization.*
524
import kotlinx.serialization.json.*
525
import kotlinx.serialization.modules.*
526
import java.time.LocalDateTime
527
import java.time.format.DateTimeFormatter
528
529
// Custom serializer for LocalDateTime
530
object LocalDateTimeSerializer : KSerializer<LocalDateTime> {
531
private val formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME
532
override val descriptor = PrimitiveSerialDescriptor("LocalDateTime", PrimitiveKind.STRING)
533
override fun serialize(encoder: Encoder, value: LocalDateTime) = encoder.encodeString(value.format(formatter))
534
override fun deserialize(decoder: Decoder): LocalDateTime = LocalDateTime.parse(decoder.decodeString(), formatter)
535
}
536
537
@Serializable
538
data class Event(
539
val name: String,
540
@Serializable(LocalDateTimeSerializer::class)
541
val timestamp: LocalDateTime
542
)
543
544
// Configure Json with custom serializers
545
val customJson = Json {
546
serializersModule = SerializersModule {
547
contextual(LocalDateTime::class, LocalDateTimeSerializer)
548
}
549
}
550
551
val event = Event("Meeting", LocalDateTime.now())
552
val encoded = customJson.encodeToString(event)
553
val decoded = customJson.decodeFromString<Event>(encoded)
554
```
555
556
## Configuration Inheritance
557
558
Json instances can inherit configuration from other instances.
559
560
```kotlin
561
import kotlinx.serialization.json.*
562
563
// Base configuration
564
val baseJson = Json {
565
ignoreUnknownKeys = true
566
isLenient = true
567
}
568
569
// Inherit and extend configuration
570
val extendedJson = Json(from = baseJson) {
571
prettyPrint = true
572
encodeDefaults = true
573
// ignoreUnknownKeys and isLenient are inherited
574
}
575
576
// Production vs Development configurations
577
val developmentJson = Json {
578
prettyPrint = true
579
encodeDefaults = true
580
allowComments = true
581
allowTrailingComma = true
582
}
583
584
val productionJson = Json(from = developmentJson) {
585
prettyPrint = false
586
allowComments = false
587
allowTrailingComma = false
588
// Other settings inherited from development
589
}
590
```