0
# JSON Builder DSL
1
2
Fluent DSL for constructing JSON objects and arrays with type-safe builder functions. The builder DSL provides an intuitive way to create JsonElement structures programmatically.
3
4
## Capabilities
5
6
### Object Builder
7
8
Create JSON objects using a fluent builder DSL.
9
10
```kotlin { .api }
11
/**
12
* Builds a JsonObject using a type-safe DSL
13
* @param builderAction Lambda with receiver for building the object
14
* @return Constructed JsonObject
15
*/
16
fun buildJsonObject(builderAction: JsonObjectBuilder.() -> Unit): JsonObject
17
18
/**
19
* Builder interface for constructing JSON objects
20
*/
21
interface JsonObjectBuilder {
22
/**
23
* Add a JsonElement value
24
*/
25
fun put(key: String, value: JsonElement)
26
27
/**
28
* Add a string value (null creates JsonNull)
29
*/
30
fun put(key: String, value: String?)
31
32
/**
33
* Add a number value (null creates JsonNull)
34
*/
35
fun put(key: String, value: Number?)
36
37
/**
38
* Add a boolean value (null creates JsonNull)
39
*/
40
fun put(key: String, value: Boolean?)
41
42
/**
43
* Add a nested JSON object
44
*/
45
fun putJsonObject(key: String, builderAction: JsonObjectBuilder.() -> Unit)
46
47
/**
48
* Add a nested JSON array
49
*/
50
fun putJsonArray(key: String, builderAction: JsonArrayBuilder.() -> Unit)
51
}
52
```
53
54
**Usage Examples:**
55
56
```kotlin
57
// Simple object construction
58
val userObject = buildJsonObject {
59
put("id", 123)
60
put("name", "Alice")
61
put("email", "alice@example.com")
62
put("isActive", true)
63
put("lastLogin", null as String?) // Creates JsonNull
64
}
65
66
// Nested object construction
67
val profileObject = buildJsonObject {
68
put("userId", 456)
69
70
putJsonObject("personal") {
71
put("firstName", "Bob")
72
put("lastName", "Smith")
73
put("age", 30)
74
}
75
76
putJsonObject("contact") {
77
put("email", "bob@example.com")
78
put("phone", "555-1234")
79
put("address", null as String?)
80
}
81
82
putJsonArray("roles") {
83
add("user")
84
add("admin")
85
add("moderator")
86
}
87
}
88
89
// Dynamic object construction
90
fun createApiResponse(success: Boolean, message: String, data: Map<String, Any>? = null) = buildJsonObject {
91
put("success", success)
92
put("message", message)
93
put("timestamp", System.currentTimeMillis())
94
95
if (data != null) {
96
putJsonObject("data") {
97
data.forEach { (key, value) ->
98
when (value) {
99
is String -> put(key, value)
100
is Number -> put(key, value)
101
is Boolean -> put(key, value)
102
else -> put(key, value.toString())
103
}
104
}
105
}
106
}
107
}
108
```
109
110
### Array Builder
111
112
Create JSON arrays using a fluent builder DSL.
113
114
```kotlin { .api }
115
/**
116
* Builds a JsonArray using a type-safe DSL
117
* @param builderAction Lambda with receiver for building the array
118
* @return Constructed JsonArray
119
*/
120
fun buildJsonArray(builderAction: JsonArrayBuilder.() -> Unit): JsonArray
121
122
/**
123
* Builder interface for constructing JSON arrays
124
*/
125
interface JsonArrayBuilder {
126
/**
127
* Add a JsonElement value
128
*/
129
fun add(value: JsonElement)
130
131
/**
132
* Add a string value (null creates JsonNull)
133
*/
134
fun add(value: String?)
135
136
/**
137
* Add a number value (null creates JsonNull)
138
*/
139
fun add(value: Number?)
140
141
/**
142
* Add a boolean value (null creates JsonNull)
143
*/
144
fun add(value: Boolean?)
145
146
/**
147
* Add a nested JSON object
148
*/
149
fun addJsonObject(builderAction: JsonObjectBuilder.() -> Unit)
150
151
/**
152
* Add a nested JSON array
153
*/
154
fun addJsonArray(builderAction: JsonArrayBuilder.() -> Unit)
155
}
156
```
157
158
**Usage Examples:**
159
160
```kotlin
161
// Simple array construction
162
val numbersArray = buildJsonArray {
163
add(1)
164
add(2)
165
add(3)
166
add(null as Int?) // Creates JsonNull
167
}
168
169
val mixedArray = buildJsonArray {
170
add("hello")
171
add(42)
172
add(true)
173
add(3.14)
174
}
175
176
// Nested array construction
177
val complexArray = buildJsonArray {
178
// Add primitive values
179
add("item1")
180
add("item2")
181
182
// Add nested object
183
addJsonObject {
184
put("type", "object")
185
put("value", 123)
186
}
187
188
// Add nested array
189
addJsonArray {
190
add("nested1")
191
add("nested2")
192
add("nested3")
193
}
194
}
195
196
// Array of objects
197
val usersArray = buildJsonArray {
198
addJsonObject {
199
put("id", 1)
200
put("name", "Alice")
201
put("role", "admin")
202
}
203
204
addJsonObject {
205
put("id", 2)
206
put("name", "Bob")
207
put("role", "user")
208
}
209
210
addJsonObject {
211
put("id", 3)
212
put("name", "Charlie")
213
put("role", "moderator")
214
}
215
}
216
```
217
218
### Complex Nested Structures
219
220
Build complex nested JSON structures combining objects and arrays.
221
222
**Usage Examples:**
223
224
```kotlin
225
// E-commerce product catalog example
226
val catalogJson = buildJsonObject {
227
put("catalogId", "electronics-2024")
228
put("version", "1.2")
229
put("lastUpdated", "2024-01-15T10:30:00Z")
230
231
putJsonArray("categories") {
232
addJsonObject {
233
put("id", "smartphones")
234
put("name", "Smartphones")
235
236
putJsonArray("products") {
237
addJsonObject {
238
put("sku", "PHONE-001")
239
put("name", "SuperPhone Pro")
240
put("price", 999.99)
241
put("inStock", true)
242
243
putJsonArray("features") {
244
add("5G connectivity")
245
add("Wireless charging")
246
add("Triple camera")
247
}
248
249
putJsonObject("specifications") {
250
put("screenSize", "6.7 inches")
251
put("storage", "256 GB")
252
put("ram", "12 GB")
253
put("batteryLife", "24 hours")
254
}
255
}
256
257
addJsonObject {
258
put("sku", "PHONE-002")
259
put("name", "BasicPhone")
260
put("price", 299.99)
261
put("inStock", false)
262
263
putJsonArray("features") {
264
add("Long battery life")
265
add("Durable design")
266
}
267
}
268
}
269
}
270
271
addJsonObject {
272
put("id", "laptops")
273
put("name", "Laptops")
274
275
putJsonArray("products") {
276
addJsonObject {
277
put("sku", "LAPTOP-001")
278
put("name", "WorkBook Pro")
279
put("price", 1599.99)
280
put("inStock", true)
281
}
282
}
283
}
284
}
285
286
putJsonObject("metadata") {
287
put("totalCategories", 2)
288
put("totalProducts", 3)
289
putJsonArray("supportedCurrencies") {
290
add("USD")
291
add("EUR")
292
add("GBP")
293
}
294
}
295
}
296
```
297
298
### Dynamic Construction Patterns
299
300
Common patterns for building JSON structures dynamically.
301
302
**Usage Examples:**
303
304
```kotlin
305
// Build object from map data
306
fun mapToJsonObject(data: Map<String, Any?>) = buildJsonObject {
307
data.forEach { (key, value) ->
308
when (value) {
309
null -> put(key, null as String?)
310
is String -> put(key, value)
311
is Number -> put(key, value)
312
is Boolean -> put(key, value)
313
is List<*> -> putJsonArray(key) {
314
value.forEach { item ->
315
when (item) {
316
is String -> add(item)
317
is Number -> add(item)
318
is Boolean -> add(item)
319
else -> add(item.toString())
320
}
321
}
322
}
323
is Map<*, *> -> putJsonObject(key) {
324
@Suppress("UNCHECKED_CAST")
325
val stringMap = value as Map<String, Any?>
326
stringMap.forEach { (k, v) ->
327
put(k, v?.toString())
328
}
329
}
330
else -> put(key, value.toString())
331
}
332
}
333
}
334
335
// Build array from collection
336
fun <T> collectionToJsonArray(items: Collection<T>, transform: JsonArrayBuilder.(T) -> Unit) = buildJsonArray {
337
items.forEach { item ->
338
transform(item)
339
}
340
}
341
342
// Usage
343
val dataMap = mapOf(
344
"name" to "Alice",
345
"age" to 30,
346
"tags" to listOf("kotlin", "developer", "tech")
347
)
348
349
val jsonFromMap = mapToJsonObject(dataMap)
350
351
val users = listOf("Alice", "Bob", "Charlie")
352
val usersJson = collectionToJsonArray(users) { name ->
353
addJsonObject {
354
put("name", name)
355
put("id", name.hashCode())
356
}
357
}
358
```
359
360
### Conditional Building
361
362
Build JSON structures with conditional logic.
363
364
**Usage Examples:**
365
366
```kotlin
367
// Conditional properties
368
fun createUserJson(
369
name: String,
370
email: String,
371
age: Int? = null,
372
isAdmin: Boolean = false,
373
preferences: Map<String, String> = emptyMap()
374
) = buildJsonObject {
375
put("name", name)
376
put("email", email)
377
378
// Conditional properties
379
if (age != null && age > 0) {
380
put("age", age)
381
}
382
383
if (isAdmin) {
384
put("role", "admin")
385
putJsonArray("permissions") {
386
add("read")
387
add("write")
388
add("delete")
389
add("admin")
390
}
391
}
392
393
// Conditional nested object
394
if (preferences.isNotEmpty()) {
395
putJsonObject("preferences") {
396
preferences.forEach { (key, value) ->
397
put(key, value)
398
}
399
}
400
}
401
}
402
403
// Usage
404
val adminUser = createUserJson(
405
name = "Admin User",
406
email = "admin@example.com",
407
age = 35,
408
isAdmin = true,
409
preferences = mapOf("theme" to "dark", "language" to "en")
410
)
411
412
val basicUser = createUserJson(
413
name = "Basic User",
414
email = "user@example.com"
415
)
416
```
417
418
### Integration with Json Class
419
420
Use builder DSL results with Json serialization methods.
421
422
**Usage Examples:**
423
424
```kotlin
425
val json = Json { prettyPrint = true }
426
427
// Build and serialize
428
val dataObject = buildJsonObject {
429
put("status", "success")
430
put("timestamp", System.currentTimeMillis())
431
432
putJsonArray("items") {
433
add("item1")
434
add("item2")
435
add("item3")
436
}
437
}
438
439
// Convert to string
440
val jsonString = json.encodeToString(JsonElement.serializer(), dataObject)
441
println(jsonString)
442
443
// Use in serialization workflows
444
@Serializable
445
data class Response(val data: JsonElement, val metadata: String)
446
447
val response = Response(
448
data = buildJsonObject {
449
put("result", "processed")
450
put("count", 42)
451
},
452
metadata = "Generated response"
453
)
454
455
val responseString = json.encodeToString(response)
456
```