0
# DSL Builders
1
2
Fluent DSL for constructing JsonObject and JsonArray instances programmatically with type-safe operations.
3
4
## Capabilities
5
6
### JsonObject Builder
7
8
DSL for constructing JsonObject instances with fluent API.
9
10
```kotlin { .api }
11
/**
12
* Builds JsonObject with the given builderAction
13
* @param builderAction Lambda with receiver for building object content
14
* @return Constructed JsonObject
15
*/
16
inline fun buildJsonObject(builderAction: JsonObjectBuilder.() -> Unit): JsonObject
17
18
/**
19
* DSL builder for JsonObject with methods to add key-value pairs
20
*/
21
class JsonObjectBuilder {
22
/**
23
* Add the given JSON element to resulting object using the given key
24
* @param key Property name
25
* @param element JsonElement value
26
* @return Previous value associated with key, or null
27
*/
28
fun put(key: String, element: JsonElement): JsonElement?
29
30
/**
31
* Add boolean value to resulting object using the given key
32
* @param key Property name
33
* @param value Boolean value (null creates JsonNull)
34
* @return Previous value associated with key, or null
35
*/
36
fun put(key: String, value: Boolean?): JsonElement?
37
38
/**
39
* Add numeric value to resulting object using the given key
40
* @param key Property name
41
* @param value Number value (null creates JsonNull)
42
* @return Previous value associated with key, or null
43
*/
44
fun put(key: String, value: Number?): JsonElement?
45
46
/**
47
* Add string value to resulting object using the given key
48
* @param key Property name
49
* @param value String value (null creates JsonNull)
50
* @return Previous value associated with key, or null
51
*/
52
fun put(key: String, value: String?): JsonElement?
53
54
/**
55
* Add null value to resulting object using the given key
56
* @param key Property name
57
* @param value Must be null literal
58
* @return Previous value associated with key, or null
59
*/
60
fun put(key: String, value: Nothing?): JsonElement?
61
}
62
63
/**
64
* Add nested JsonObject produced by builderAction to resulting object
65
* @param key Property name
66
* @param builderAction Lambda for building nested object
67
* @return Previous value associated with key, or null
68
*/
69
fun JsonObjectBuilder.putJsonObject(key: String, builderAction: JsonObjectBuilder.() -> Unit): JsonElement?
70
71
/**
72
* Add nested JsonArray produced by builderAction to resulting object
73
* @param key Property name
74
* @param builderAction Lambda for building nested array
75
* @return Previous value associated with key, or null
76
*/
77
fun JsonObjectBuilder.putJsonArray(key: String, builderAction: JsonArrayBuilder.() -> Unit): JsonElement?
78
```
79
80
**Usage Examples:**
81
82
```kotlin
83
// Basic object construction
84
val userObject = buildJsonObject {
85
put("id", 123)
86
put("name", "Alice")
87
put("active", true)
88
put("email", null) // Creates JsonNull
89
}
90
// Result: {"id":123,"name":"Alice","active":true,"email":null}
91
92
// Nested objects and arrays
93
val complexObject = buildJsonObject {
94
put("userId", 456)
95
put("profile", buildJsonObject {
96
put("firstName", "Bob")
97
put("lastName", "Smith")
98
put("age", 30)
99
})
100
put("permissions", buildJsonArray {
101
add("read")
102
add("write")
103
add("admin")
104
})
105
}
106
107
// Using put methods for different types
108
val apiResponse = buildJsonObject {
109
put("success", true)
110
put("timestamp", System.currentTimeMillis())
111
put("message", "Operation completed")
112
put("data", JsonPrimitive("custom element"))
113
}
114
115
// Nested with DSL extension functions
116
val settingsObject = buildJsonObject {
117
put("version", "1.0")
118
119
putJsonObject("database") {
120
put("host", "localhost")
121
put("port", 5432)
122
put("ssl", true)
123
}
124
125
putJsonArray("features") {
126
add("authentication")
127
add("logging")
128
add("metrics")
129
}
130
}
131
```
132
133
### JsonArray Builder
134
135
DSL for constructing JsonArray instances with fluent API.
136
137
```kotlin { .api }
138
/**
139
* Builds JsonArray with the given builderAction
140
* @param builderAction Lambda with receiver for building array content
141
* @return Constructed JsonArray
142
*/
143
inline fun buildJsonArray(builderAction: JsonArrayBuilder.() -> Unit): JsonArray
144
145
/**
146
* DSL builder for JsonArray with methods to add elements
147
*/
148
class JsonArrayBuilder {
149
/**
150
* Adds the given JSON element to resulting array
151
* @param element JsonElement to add
152
* @return Always true (similar to ArrayList specification)
153
*/
154
fun add(element: JsonElement): Boolean
155
156
/**
157
* Adds the given boolean value to resulting array
158
* @param value Boolean value (null creates JsonNull)
159
* @return Always true
160
*/
161
fun add(value: Boolean?): Boolean
162
163
/**
164
* Adds the given numeric value to resulting array
165
* @param value Number value (null creates JsonNull)
166
* @return Always true
167
*/
168
fun add(value: Number?): Boolean
169
170
/**
171
* Adds the given string value to resulting array
172
* @param value String value (null creates JsonNull)
173
* @return Always true
174
*/
175
fun add(value: String?): Boolean
176
177
/**
178
* Adds null value to resulting array
179
* @param value Must be null literal
180
* @return Always true
181
*/
182
fun add(value: Nothing?): Boolean
183
184
/**
185
* Adds the given JSON elements to resulting array
186
* @param elements Collection of JsonElements to add
187
* @return true if array was changed
188
*/
189
fun addAll(elements: Collection<JsonElement>): Boolean
190
191
/**
192
* Adds the given string values to resulting array
193
* @param values Collection of strings to add
194
* @return true if array was changed
195
*/
196
fun addAll(values: Collection<String?>): Boolean
197
198
/**
199
* Adds the given boolean values to resulting array
200
* @param values Collection of booleans to add
201
* @return true if array was changed
202
*/
203
fun addAll(values: Collection<Boolean?>): Boolean
204
205
/**
206
* Adds the given numeric values to resulting array
207
* @param values Collection of numbers to add
208
* @return true if array was changed
209
*/
210
fun addAll(values: Collection<Number?>): Boolean
211
}
212
213
/**
214
* Adds nested JsonObject produced by builderAction to resulting array
215
* @param builderAction Lambda for building nested object
216
* @return Always true
217
*/
218
fun JsonArrayBuilder.addJsonObject(builderAction: JsonObjectBuilder.() -> Unit): Boolean
219
220
/**
221
* Adds nested JsonArray produced by builderAction to resulting array
222
* @param builderAction Lambda for building nested array
223
* @return Always true
224
*/
225
fun JsonArrayBuilder.addJsonArray(builderAction: JsonArrayBuilder.() -> Unit): Boolean
226
```
227
228
**Usage Examples:**
229
230
```kotlin
231
// Basic array construction
232
val numbersArray = buildJsonArray {
233
add(1)
234
add(2.5)
235
add(3L)
236
add(null) // Creates JsonNull
237
}
238
// Result: [1,2.5,3,null]
239
240
// Mixed type array
241
val mixedArray = buildJsonArray {
242
add("string")
243
add(42)
244
add(true)
245
add(JsonPrimitive("custom"))
246
}
247
// Result: ["string",42,true,"custom"]
248
249
// Nested structures
250
val complexArray = buildJsonArray {
251
// Add simple values
252
add("header")
253
254
// Add nested object
255
addJsonObject {
256
put("id", 1)
257
put("name", "Item 1")
258
}
259
260
// Add nested array
261
addJsonArray {
262
add("nested")
263
add("values")
264
}
265
266
// Add another object
267
addJsonObject {
268
put("id", 2)
269
put("active", false)
270
}
271
}
272
273
// Using addAll for collections
274
val tags = listOf("kotlin", "json", "serialization")
275
val numbers = listOf(1, 2, 3, 4, 5)
276
val flags = listOf(true, false, true)
277
278
val collectionArray = buildJsonArray {
279
add("Collections:")
280
addAll(tags) // Add all strings
281
addAll(numbers) // Add all numbers
282
addAll(flags) // Add all booleans
283
}
284
285
// Building from existing data
286
data class User(val id: Int, val name: String)
287
val users = listOf(User(1, "Alice"), User(2, "Bob"))
288
289
val usersArray = buildJsonArray {
290
for (user in users) {
291
addJsonObject {
292
put("id", user.id)
293
put("name", user.name)
294
put("active", true)
295
}
296
}
297
}
298
```
299
300
### Advanced DSL Patterns
301
302
Combining builders for complex JSON construction.
303
304
**Usage Examples:**
305
306
```kotlin
307
// Configuration file structure
308
val configJson = buildJsonObject {
309
put("version", "2.1.0")
310
put("environment", "production")
311
312
putJsonObject("server") {
313
put("host", "0.0.0.0")
314
put("port", 8080)
315
put("ssl", true)
316
317
putJsonObject("limits") {
318
put("maxConnections", 1000)
319
put("timeout", 30000)
320
}
321
}
322
323
putJsonObject("database") {
324
put("driver", "postgresql")
325
put("host", "db.example.com")
326
put("port", 5432)
327
328
putJsonArray("replicas") {
329
addJsonObject {
330
put("host", "replica1.example.com")
331
put("port", 5432)
332
put("priority", 1)
333
}
334
addJsonObject {
335
put("host", "replica2.example.com")
336
put("port", 5432)
337
put("priority", 2)
338
}
339
}
340
}
341
342
putJsonArray("features") {
343
add("authentication")
344
add("rate-limiting")
345
add("monitoring")
346
347
addJsonObject {
348
put("name", "custom-feature")
349
put("enabled", true)
350
putJsonObject("config") {
351
put("param1", "value1")
352
put("param2", 123)
353
}
354
}
355
}
356
}
357
358
// API response format
359
fun buildApiResponse(success: Boolean, data: Any?, message: String? = null) = buildJsonObject {
360
put("success", success)
361
put("timestamp", System.currentTimeMillis())
362
363
message?.let { put("message", it) }
364
365
when (data) {
366
is Collection<*> -> putJsonArray("data") {
367
data.forEach { item ->
368
when (item) {
369
is String -> add(item)
370
is Number -> add(item)
371
is Boolean -> add(item)
372
else -> add(item.toString())
373
}
374
}
375
}
376
is Map<*, *> -> putJsonObject("data") {
377
data.forEach { (key, value) ->
378
when (value) {
379
is String -> put(key.toString(), value)
380
is Number -> put(key.toString(), value)
381
is Boolean -> put(key.toString(), value)
382
else -> put(key.toString(), value.toString())
383
}
384
}
385
}
386
else -> put("data", data?.toString())
387
}
388
}
389
```