0
# Configuration and Builder
1
2
Comprehensive configuration system for customizing JSON encoding and decoding behavior through builder pattern.
3
4
## Capabilities
5
6
### JsonBuilder
7
8
Builder class for configuring Json instances with mutable properties for all configuration options.
9
10
```kotlin { .api }
11
/**
12
* Builder for Json instance configuration provided by Json { ... } factory function
13
*/
14
class JsonBuilder {
15
/** Whether default values of Kotlin properties should be encoded. Default: false */
16
var encodeDefaults: Boolean
17
18
/** Whether null values should be encoded for nullable properties. Default: true */
19
var explicitNulls: Boolean
20
21
/** Whether encounters of unknown properties should be ignored. Default: false */
22
var ignoreUnknownKeys: Boolean
23
24
/** Removes JSON specification restriction and makes parser more liberal. Default: false */
25
var isLenient: Boolean
26
27
/** Whether resulting JSON should be pretty-printed. Default: false */
28
var prettyPrint: Boolean
29
30
/** Indent string to use with prettyPrint mode. Default: " " (4 spaces) */
31
var prettyPrintIndent: String
32
33
/** Enables coercing incorrect JSON values. Default: false */
34
var coerceInputValues: Boolean
35
36
/** Name of class descriptor property for polymorphic serialization. Default: "type" */
37
var classDiscriminator: String
38
39
/** Defines which classes should have class discriminator added. Default: POLYMORPHIC */
40
var classDiscriminatorMode: ClassDiscriminatorMode
41
42
/** Whether Json instance makes use of JsonNames annotation. Default: true */
43
var useAlternativeNames: Boolean
44
45
/** JsonNamingStrategy for all properties in classes. Default: null */
46
var namingStrategy: JsonNamingStrategy?
47
48
/** Enables decoding enum values in case-insensitive manner. Default: false */
49
var decodeEnumsCaseInsensitive: Boolean
50
51
/** Allows parser to accept trailing commas. Default: false */
52
var allowTrailingComma: Boolean
53
54
/** Allows parser to accept C/Java-style comments. Default: false */
55
var allowComments: Boolean
56
57
/** Removes restriction on special floating-point values (NaN, Infinity). Default: false */
58
var allowSpecialFloatingPointValues: Boolean
59
60
/** Enables structured objects to be serialized as map keys. Default: false */
61
var allowStructuredMapKeys: Boolean
62
63
/** Switches polymorphic serialization to array format. Default: false */
64
var useArrayPolymorphism: Boolean
65
66
/** Module with contextual and polymorphic serializers. Default: EmptySerializersModule */
67
var serializersModule: SerializersModule
68
}
69
```
70
71
### JsonConfiguration
72
73
Immutable configuration object containing all Json behavior settings.
74
75
```kotlin { .api }
76
/**
77
* Configuration of current Json instance available through Json.configuration
78
* Standalone configuration object is read-only and cannot create new Json instances
79
*/
80
class JsonConfiguration(
81
val encodeDefaults: Boolean = false,
82
val ignoreUnknownKeys: Boolean = false,
83
val isLenient: Boolean = false,
84
val allowStructuredMapKeys: Boolean = false,
85
val prettyPrint: Boolean = false,
86
val explicitNulls: Boolean = true,
87
val prettyPrintIndent: String = " ",
88
val coerceInputValues: Boolean = false,
89
val useArrayPolymorphism: Boolean = false,
90
val classDiscriminator: String = "type",
91
val allowSpecialFloatingPointValues: Boolean = false,
92
val useAlternativeNames: Boolean = true,
93
val namingStrategy: JsonNamingStrategy? = null,
94
val decodeEnumsCaseInsensitive: Boolean = false,
95
val allowTrailingComma: Boolean = false,
96
val allowComments: Boolean = false,
97
val classDiscriminatorMode: ClassDiscriminatorMode = ClassDiscriminatorMode.POLYMORPHIC
98
)
99
```
100
101
## Configuration Options
102
103
### Encoding Behavior
104
105
Control how Kotlin objects are encoded to JSON.
106
107
**Usage Examples:**
108
109
```kotlin
110
@Serializable
111
data class User(val name: String, val age: Int = 25, val email: String? = null)
112
113
// encodeDefaults: Include properties with default values
114
val withDefaults = Json { encodeDefaults = true }
115
val user = User("Alice")
116
println(withDefaults.encodeToString(user))
117
// {"name":"Alice","age":25,"email":null}
118
119
val withoutDefaults = Json { encodeDefaults = false }
120
println(withoutDefaults.encodeToString(user))
121
// {"name":"Alice"}
122
123
// explicitNulls: Control null value encoding
124
val explicitNulls = Json { explicitNulls = true }
125
val implicitNulls = Json { explicitNulls = false }
126
127
val userWithNull = User("Bob", email = null)
128
println(explicitNulls.encodeToString(userWithNull))
129
// {"name":"Bob","email":null}
130
131
println(implicitNulls.encodeToString(userWithNull))
132
// {"name":"Bob"}
133
134
// prettyPrint: Format JSON for readability
135
val pretty = Json {
136
prettyPrint = true
137
prettyPrintIndent = " " // 2 spaces
138
}
139
println(pretty.encodeToString(user))
140
/*
141
{
142
"name": "Alice",
143
"age": 25
144
}
145
*/
146
```
147
148
### Decoding Behavior
149
150
Control how JSON is decoded to Kotlin objects.
151
152
**Usage Examples:**
153
154
```kotlin
155
@Serializable
156
data class Config(val timeout: Int, val retries: Int)
157
158
// ignoreUnknownKeys: Handle extra properties in JSON
159
val lenient = Json { ignoreUnknownKeys = true }
160
val strict = Json { ignoreUnknownKeys = false }
161
162
val jsonWithExtra = """{"timeout":5000,"retries":3,"unknown":"value"}"""
163
164
val config1 = lenient.decodeFromString<Config>(jsonWithExtra)
165
// Success: Config(timeout=5000, retries=3)
166
167
// strict.decodeFromString<Config>(jsonWithExtra)
168
// Would throw SerializationException
169
170
// coerceInputValues: Handle invalid values
171
val coercing = Json { coerceInputValues = true }
172
173
enum class Status { ACTIVE, INACTIVE }
174
@Serializable
175
data class Account(val id: Int = 1, val status: Status = Status.ACTIVE)
176
177
val invalidJson = """{"id":null,"status":"UNKNOWN"}"""
178
val account = coercing.decodeFromString<Account>(invalidJson)
179
// Result: Account(id=1, status=ACTIVE) - uses defaults for invalid values
180
181
// isLenient: Accept malformed JSON
182
val lenientParser = Json { isLenient = true }
183
val malformedJson = """{key: "value", another: 123}""" // Unquoted keys
184
val parsed = lenientParser.parseToJsonElement(malformedJson)
185
```
186
187
### Special Value Handling
188
189
Handle special cases like floating-point values and structured map keys.
190
191
**Usage Examples:**
192
193
```kotlin
194
// allowSpecialFloatingPointValues: Handle NaN and Infinity
195
val specialFloats = Json { allowSpecialFloatingPointValues = true }
196
197
val floats = listOf(1.0, 2.0, Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY)
198
val encoded = specialFloats.encodeToString(floats)
199
// [1.0,2.0,NaN,Infinity,-Infinity]
200
201
val decoded = specialFloats.decodeFromString<List<Double>>(encoded)
202
203
// allowStructuredMapKeys: Use objects as map keys
204
val structuredKeys = Json { allowStructuredMapKeys = true }
205
206
@Serializable
207
data class Point(val x: Int, val y: Int)
208
209
val mapWithObjectKeys = mapOf(
210
Point(1, 2) to "first",
211
Point(3, 4) to "second"
212
)
213
214
val encoded = structuredKeys.encodeToString(mapWithObjectKeys)
215
// [{"x":1,"y":2},"first",{"x":3,"y":4},"second"] - flat array format
216
```
217
218
### Polymorphism Configuration
219
220
Control how polymorphic types are handled during serialization.
221
222
**Usage Examples:**
223
224
```kotlin
225
@Serializable
226
sealed class Shape
227
@Serializable
228
data class Circle(val radius: Double) : Shape()
229
@Serializable
230
data class Rectangle(val width: Double, val height: Double) : Shape()
231
232
// classDiscriminator: Change discriminator property name
233
val customDiscriminator = Json {
234
classDiscriminator = "shapeType"
235
}
236
237
val circle: Shape = Circle(5.0)
238
val encoded = customDiscriminator.encodeToString(circle)
239
// {"shapeType":"Circle","radius":5.0}
240
241
// useArrayPolymorphism: Use array format for polymorphism
242
val arrayPoly = Json { useArrayPolymorphism = true }
243
val arrayEncoded = arrayPoly.encodeToString(circle)
244
// ["Circle",{"radius":5.0}]
245
246
// classDiscriminatorMode: Control when discriminator is added
247
val allObjects = Json {
248
classDiscriminatorMode = ClassDiscriminatorMode.ALL_JSON_OBJECTS
249
}
250
251
@Serializable
252
data class Container(val shape: Shape, val metadata: Map<String, String>)
253
254
val container = Container(circle, mapOf("color" to "red"))
255
// Adds discriminator to all JSON objects, not just polymorphic ones
256
```
257
258
### Comments and Trailing Commas
259
260
Enable relaxed JSON parsing for development and configuration files.
261
262
**Usage Examples:**
263
264
```kotlin
265
val relaxed = Json {
266
allowComments = true
267
allowTrailingComma = true
268
ignoreUnknownKeys = true
269
}
270
271
val jsonWithComments = """
272
{
273
// Configuration file
274
"database": {
275
"host": "localhost", // Development host
276
"port": 5432,
277
/*
278
* Connection pool settings
279
*/
280
"maxConnections": 10,
281
}, // Trailing comma allowed
282
"features": [
283
"auth",
284
"logging", // Another trailing comma
285
]
286
}
287
"""
288
289
val config = relaxed.parseToJsonElement(jsonWithComments)
290
```
291
292
### Serializers Module Integration
293
294
Configure custom serializers and polymorphic serialization rules.
295
296
**Usage Examples:**
297
298
```kotlin
299
val module = SerializersModule {
300
polymorphic(Shape::class) {
301
subclass(Circle::class)
302
subclass(Rectangle::class)
303
}
304
305
contextual(UUID::class, UUIDSerializer)
306
}
307
308
val configuredJson = Json {
309
serializersModule = module
310
classDiscriminator = "type"
311
ignoreUnknownKeys = true
312
}
313
314
// Now polymorphic serialization works automatically
315
val shapes: List<Shape> = listOf(Circle(3.0), Rectangle(4.0, 5.0))
316
val encoded = configuredJson.encodeToString(shapes)
317
val decoded = configuredJson.decodeFromString<List<Shape>>(encoded)
318
```