0
# JSON Processing
1
2
Comprehensive JSON parsing, generation, and manipulation capabilities through JsonSlurper for parsing JSON data and JsonBuilder for creating JSON output with full type safety and streaming support.
3
4
## Capabilities
5
6
### JSON Parsing with JsonSlurper
7
8
High-performance JSON parser that converts JSON text into Groovy data structures (Maps, Lists, primitive types).
9
10
```java { .api }
11
/**
12
* Main JSON parser that converts JSON text into native Groovy objects
13
*/
14
class JsonSlurper {
15
/**
16
* Parse JSON from a String
17
*/
18
Object parseText(String text);
19
20
/**
21
* Parse JSON from a Reader
22
*/
23
Object parse(Reader reader);
24
25
/**
26
* Parse JSON from a File
27
*/
28
Object parse(File file);
29
30
/**
31
* Parse JSON from a URL
32
*/
33
Object parse(URL url);
34
35
/**
36
* Parse JSON from an InputStream with specified encoding
37
*/
38
Object parse(InputStream input, String charset);
39
40
/**
41
* Parse JSON from a character array
42
*/
43
Object parse(char[] text);
44
45
/**
46
* Set the parser type for different performance characteristics
47
*/
48
void setType(JsonParserType type);
49
}
50
51
/**
52
* Enumeration of available JSON parser implementations
53
*/
54
enum JsonParserType {
55
CHARACTER_SOURCE, // Default parser, good balance of speed and memory
56
LAX, // Lenient parser, allows non-standard JSON
57
INDEX_OVERLAY // Fastest parser for large documents
58
}
59
```
60
61
**Usage Examples:**
62
63
```groovy
64
import groovy.json.JsonSlurper
65
66
def jsonSlurper = new JsonSlurper()
67
68
// Parse simple JSON string
69
def result = jsonSlurper.parseText('{"name": "John", "age": 30}')
70
assert result.name == "John"
71
assert result.age == 30
72
73
// Parse JSON array
74
def list = jsonSlurper.parseText('[1, 2, 3, {"nested": true}]')
75
assert list.size() == 4
76
assert list[3].nested == true
77
78
// Parse from file
79
def config = jsonSlurper.parse(new File('config.json'))
80
81
// Parse from URL
82
def apiData = jsonSlurper.parse(new URL('https://api.example.com/data'))
83
84
// Configure parser type for performance
85
jsonSlurper.type = JsonParserType.LAX
86
def relaxedJson = jsonSlurper.parseText('{name: "unquoted keys allowed"}')
87
```
88
89
### JSON Generation with JsonBuilder
90
91
Fluent API for creating JSON output with support for nested structures and streaming.
92
93
```java { .api }
94
/**
95
* Builder for creating JSON output using a fluent API
96
*/
97
class JsonBuilder {
98
/**
99
* Create empty JsonBuilder
100
*/
101
JsonBuilder();
102
103
/**
104
* Create JsonBuilder with initial content
105
*/
106
JsonBuilder(Object content);
107
108
/**
109
* Build JSON using closure-based DSL
110
*/
111
void call(Closure closure);
112
113
/**
114
* Build JSON with single argument
115
*/
116
void call(Object... args);
117
118
/**
119
* Get the built JSON as a String
120
*/
121
String toString();
122
123
/**
124
* Get the built content as native Groovy object
125
*/
126
Object getContent();
127
128
/**
129
* Write JSON to a Writer
130
*/
131
Writer writeTo(Writer writer);
132
}
133
134
/**
135
* Memory-efficient streaming JSON builder for large documents
136
*/
137
class StreamingJsonBuilder {
138
/**
139
* Create StreamingJsonBuilder with Writer output
140
*/
141
StreamingJsonBuilder(Writer writer);
142
143
/**
144
* Create StreamingJsonBuilder with OutputStream
145
*/
146
StreamingJsonBuilder(OutputStream output);
147
148
/**
149
* Create StreamingJsonBuilder with OutputStream and encoding
150
*/
151
StreamingJsonBuilder(OutputStream output, String charset);
152
153
/**
154
* Build JSON using closure-based DSL
155
*/
156
void call(Closure closure);
157
158
/**
159
* Build JSON with arguments
160
*/
161
void call(Object... args);
162
}
163
```
164
165
**Usage Examples:**
166
167
```groovy
168
import groovy.json.JsonBuilder
169
import groovy.json.StreamingJsonBuilder
170
171
// Simple JSON building
172
def builder = new JsonBuilder()
173
builder {
174
name "John Doe"
175
age 30
176
address {
177
street "123 Main St"
178
city "Anytown"
179
zipCode "12345"
180
}
181
hobbies(["reading", "swimming", "coding"])
182
}
183
println builder.toString()
184
// Output: {"name":"John Doe","age":30,"address":{"street":"123 Main St","city":"Anytown","zipCode":"12345"},"hobbies":["reading","swimming","coding"]}
185
186
// Build from existing data
187
def person = [name: "Jane", age: 25]
188
def personJson = new JsonBuilder(person)
189
190
// Complex nested structure
191
def complexBuilder = new JsonBuilder()
192
complexBuilder {
193
users {
194
user1 {
195
name "Alice"
196
roles(["admin", "user"])
197
settings {
198
theme "dark"
199
notifications true
200
}
201
}
202
user2 {
203
name "Bob"
204
roles(["user"])
205
}
206
}
207
metadata {
208
version "1.0"
209
timestamp new Date().time
210
}
211
}
212
213
// Streaming builder for large documents
214
def output = new StringWriter()
215
def streamingBuilder = new StreamingJsonBuilder(output)
216
streamingBuilder {
217
largeDataSet {
218
(1..1000).each { i ->
219
"item$i" {
220
id i
221
value "data-$i"
222
}
223
}
224
}
225
}
226
```
227
228
### JSON Generation Configuration
229
230
Advanced JSON output formatting and configuration options.
231
232
```java { .api }
233
/**
234
* Configuration options for JSON generation
235
*/
236
class JsonGenerator {
237
/**
238
* Create generator with default options
239
*/
240
static JsonGenerator createDefault();
241
242
/**
243
* Create generator with custom options
244
*/
245
static JsonGenerator create(JsonGenerator.Options options);
246
247
/**
248
* Convert object to JSON string
249
*/
250
String toJson(Object object);
251
252
/**
253
* Write object as JSON to Writer
254
*/
255
void writeJson(Object object, Writer writer);
256
257
/**
258
* Configuration options for JSON generation
259
*/
260
static class Options {
261
Options excludeNulls();
262
Options excludeFieldsByName(String... names);
263
Options excludeFieldsByType(Class... types);
264
Options addConverter(Class type, Closure converter);
265
Options dateFormat(String format);
266
Options disableUnicodeEscaping();
267
}
268
}
269
```
270
271
**Usage Examples:**
272
273
```groovy
274
import groovy.json.JsonGenerator
275
276
// Custom JSON generation with options
277
def generator = JsonGenerator.create {
278
excludeNulls()
279
dateFormat('yyyy-MM-dd')
280
excludeFieldsByName('password', 'secret')
281
}
282
283
def user = [
284
name: "John",
285
password: "secret123",
286
email: "john@example.com",
287
lastLogin: new Date(),
288
metadata: null
289
]
290
291
def json = generator.toJson(user)
292
// Output excludes 'password' and 'metadata' fields, formats date
293
294
// Custom type converters
295
def customGenerator = JsonGenerator.create {
296
addConverter(URL) { url -> url.toString() }
297
addConverter(File) { file -> file.absolutePath }
298
}
299
```
300
301
### JSON Path Navigation
302
303
Navigate and extract data from parsed JSON using GPath expressions.
304
305
**Usage Examples:**
306
307
```groovy
308
import groovy.json.JsonSlurper
309
310
def jsonText = '''
311
{
312
"company": "TechCorp",
313
"employees": [
314
{"name": "Alice", "department": "Engineering", "salary": 85000},
315
{"name": "Bob", "department": "Marketing", "salary": 65000},
316
{"name": "Carol", "department": "Engineering", "salary": 90000}
317
],
318
"locations": {
319
"headquarters": "New York",
320
"branches": ["California", "Texas", "Florida"]
321
}
322
}
323
'''
324
325
def company = new JsonSlurper().parseText(jsonText)
326
327
// Simple property access
328
assert company.company == "TechCorp"
329
330
// Array access and filtering
331
def engineers = company.employees.findAll { it.department == "Engineering" }
332
assert engineers.size() == 2
333
334
// Nested property access
335
assert company.locations.headquarters == "New York"
336
assert company.locations.branches[0] == "California"
337
338
// Sum calculations
339
def totalSalary = company.employees.sum { it.salary }
340
assert totalSalary == 240000
341
342
// Find specific employee
343
def alice = company.employees.find { it.name == "Alice" }
344
assert alice.salary == 85000
345
```
346
347
### Error Handling and Validation
348
349
Handle malformed JSON and validate JSON structure.
350
351
**Usage Examples:**
352
353
```groovy
354
import groovy.json.JsonSlurper
355
import groovy.json.JsonException
356
357
def jsonSlurper = new JsonSlurper()
358
359
try {
360
def result = jsonSlurper.parseText('{"invalid": json}')
361
} catch (JsonException e) {
362
println "Invalid JSON: ${e.message}"
363
}
364
365
// Validate JSON structure
366
def validateUser = { json ->
367
def required = ['name', 'email', 'age']
368
def missing = required.findAll { !json.containsKey(it) }
369
if (missing) {
370
throw new IllegalArgumentException("Missing required fields: $missing")
371
}
372
return json
373
}
374
375
def userData = jsonSlurper.parseText('{"name": "John", "email": "john@example.com", "age": 30}')
376
validateUser(userData)
377
```
378
379
## Types
380
381
### JSON Parser Types
382
383
```java { .api }
384
/**
385
* Exception thrown when JSON parsing fails
386
*/
387
class JsonException extends RuntimeException {
388
JsonException(String message);
389
JsonException(String message, Throwable cause);
390
}
391
392
/**
393
* Parser type enumeration for different parsing strategies
394
*/
395
enum JsonParserType {
396
/**
397
* Default character-based parser with good balance of performance and memory usage
398
*/
399
CHARACTER_SOURCE,
400
401
/**
402
* Lenient parser that accepts non-standard JSON formats
403
*/
404
LAX,
405
406
/**
407
* Fastest parser optimized for large documents using index overlays
408
*/
409
INDEX_OVERLAY
410
}
411
```
412
413
### JSON Builder Types
414
415
```java { .api }
416
/**
417
* Options for configuring JSON output generation
418
*/
419
interface JsonGenerator.Options {
420
/**
421
* Exclude null values from JSON output
422
*/
423
Options excludeNulls();
424
425
/**
426
* Exclude specific fields by name
427
*/
428
Options excludeFieldsByName(String... names);
429
430
/**
431
* Exclude fields of specific types
432
*/
433
Options excludeFieldsByType(Class... types);
434
435
/**
436
* Add custom type converter
437
*/
438
Options addConverter(Class type, Closure converter);
439
440
/**
441
* Set date formatting pattern
442
*/
443
Options dateFormat(String format);
444
445
/**
446
* Disable Unicode character escaping
447
*/
448
Options disableUnicodeEscaping();
449
}
450
```