0
# JSON Processing
1
2
Groovy provides comprehensive JSON support through JsonSlurper for parsing and JsonBuilder for generation, with multiple parser types and flexible configuration options.
3
4
## JSON Parsing
5
6
### JsonSlurper
7
8
Primary class for parsing JSON from various sources with configurable parser types.
9
10
```groovy { .api }
11
class JsonSlurper {
12
JsonSlurper()
13
14
// Core parsing methods
15
Object parseText(String text)
16
Object parse(File file)
17
Object parse(File file, String charset)
18
Object parse(InputStream inputStream)
19
Object parse(InputStream inputStream, String charset)
20
Object parse(URL url)
21
Object parse(URL url, String charset)
22
Object parse(Reader reader)
23
Object parse(char[] chars)
24
Object parse(byte[] bytes)
25
Object parse(byte[] bytes, String charset)
26
Object parse(Path path)
27
Object parse(Path path, String charset)
28
29
// URL parsing with parameters
30
Object parse(URL url, Map params)
31
Object parse(Map params, URL url)
32
Object parse(URL url, Map params, String charset)
33
Object parse(Map params, URL url, String charset)
34
35
// Configuration methods
36
JsonSlurper setType(JsonParserType type)
37
JsonParserType getType()
38
39
int getMaxSizeForInMemory()
40
JsonSlurper setMaxSizeForInMemory(int maxSizeForInMemory)
41
42
boolean isChop()
43
JsonSlurper setChop(boolean chop)
44
45
boolean isLazyChop()
46
JsonSlurper setLazyChop(boolean lazyChop)
47
48
boolean isCheckDates()
49
JsonSlurper setCheckDates(boolean checkDates)
50
}
51
```
52
53
### JsonParserType
54
55
Enumeration of available JSON parser implementations.
56
57
```groovy { .api }
58
enum JsonParserType {
59
CHAR_BUFFER, // Default parser type
60
CHARACTER_SOURCE,
61
INDEX_OVERLAY,
62
LAX
63
}
64
```
65
66
Usage examples:
67
```groovy
68
import groovy.json.JsonSlurper
69
70
def jsonSlurper = new JsonSlurper()
71
72
// Parse JSON string
73
def jsonText = '{"name": "John", "age": 30, "city": "New York"}'
74
def result = jsonSlurper.parseText(jsonText)
75
assert result.name == 'John'
76
assert result.age == 30
77
78
// Parse JSON from file
79
def file = new File('data.json')
80
def data = jsonSlurper.parse(file)
81
82
// Parse JSON from URL
83
def url = new URL('https://api.example.com/data.json')
84
def apiData = jsonSlurper.parse(url)
85
86
// Use different parser types
87
def laxSlurper = new JsonSlurper().setType(JsonParserType.LAX)
88
def relaxedJson = laxSlurper.parseText('{name: "John", age: 30}') // Unquoted keys allowed
89
90
// Configure parser settings
91
def configuredSlurper = new JsonSlurper()
92
.setType(JsonParserType.LAX)
93
.setMaxSizeForInMemory(1000000)
94
.setChop(true)
95
.setCheckDates(false)
96
97
// Parse with URL parameters
98
def params = [timeout: 5000, maxRetries: 3]
99
def apiData = jsonSlurper.parse(url, params)
100
```
101
102
## JSON Generation
103
104
### JsonBuilder
105
106
Builder for constructing JSON data structures programmatically.
107
108
```groovy { .api }
109
class JsonBuilder implements Writable {
110
JsonBuilder()
111
JsonBuilder(Object content)
112
113
Object call()
114
Object call(Closure c)
115
Object call(Object... args)
116
Object call(Iterable coll, Closure c)
117
Object call(Object[] array, Closure c)
118
Object call(Map m)
119
Object call(Map m, Closure c)
120
Object call(List l)
121
Object call(List l, Closure c)
122
123
String toString()
124
String toPrettyString()
125
Writer writeTo(Writer out)
126
127
Object getContent()
128
}
129
```
130
131
Usage examples:
132
```groovy
133
import groovy.json.JsonBuilder
134
135
// Simple object construction
136
def builder = new JsonBuilder()
137
builder {
138
name 'John'
139
age 30
140
city 'New York'
141
hobbies(['reading', 'swimming'])
142
}
143
println builder.toPrettyString()
144
145
// Array of objects
146
builder = new JsonBuilder()
147
builder([
148
[name: 'John', age: 30],
149
[name: 'Jane', age: 25]
150
])
151
152
// Nested structures
153
builder = new JsonBuilder()
154
builder {
155
user {
156
name 'John'
157
details {
158
age 30
159
address {
160
street '123 Main St'
161
city 'New York'
162
}
163
}
164
}
165
}
166
167
// Dynamic content with closures
168
def users = [
169
[name: 'John', age: 30],
170
[name: 'Jane', age: 25]
171
]
172
173
builder = new JsonBuilder(users) { person ->
174
name person.name
175
age person.age
176
adult person.age >= 18
177
}
178
```
179
180
### StreamingJsonBuilder
181
182
Memory-efficient JSON builder for large data structures using streaming output.
183
184
```groovy { .api }
185
class StreamingJsonBuilder implements Writable {
186
StreamingJsonBuilder(Writer writer)
187
StreamingJsonBuilder(Writer writer, JsonGenerator generator)
188
189
Object call(Closure c)
190
Object call(Object... args)
191
Object call(Iterable coll, Closure c)
192
Object call(Object[] array, Closure c)
193
Object call(Map m)
194
Object call(Map m, Closure c)
195
Object call(List l)
196
Object call(List l, Closure c)
197
198
Writer writeTo(Writer out)
199
Writer getWriter()
200
}
201
```
202
203
Usage example:
204
```groovy
205
import groovy.json.StreamingJsonBuilder
206
207
def writer = new StringWriter()
208
def builder = new StreamingJsonBuilder(writer)
209
210
builder {
211
users([
212
[name: 'John', age: 30],
213
[name: 'Jane', age: 25]
214
]) { user ->
215
name user.name
216
age user.age
217
adult user.age >= 18
218
}
219
}
220
221
println writer.toString()
222
```
223
224
## JSON Utilities
225
226
### JsonOutput
227
228
Utility class for JSON serialization and formatting.
229
230
```groovy { .api }
231
class JsonOutput {
232
static String toJson(Object object)
233
static String prettyPrint(String jsonPayload)
234
static void prettyPrint(String jsonPayload, Writer writer)
235
236
static String toJson(Map m)
237
static String toJson(Collection c)
238
static String toJson(Object[] array)
239
static String toJson(boolean b)
240
static String toJson(Number n)
241
static String toJson(Character c)
242
static String toJson(String s)
243
static String toJson(Date date)
244
static String toJson(Calendar cal)
245
static String toJson(UUID uuid)
246
static String toJson(URL url)
247
static String toJson(Closure closure)
248
}
249
```
250
251
Usage examples:
252
```groovy
253
import groovy.json.JsonOutput
254
255
// Convert objects to JSON
256
def person = [name: 'John', age: 30, hobbies: ['reading', 'swimming']]
257
def json = JsonOutput.toJson(person)
258
println json // {"name":"John","age":30,"hobbies":["reading","swimming"]}
259
260
// Pretty print JSON
261
def prettyJson = JsonOutput.prettyPrint(json)
262
println prettyJson
263
264
// Convert various types
265
assert JsonOutput.toJson([1, 2, 3]) == '[1,2,3]'
266
assert JsonOutput.toJson(true) == 'true'
267
assert JsonOutput.toJson(null) == 'null'
268
assert JsonOutput.toJson('hello') == '"hello"'
269
```
270
271
### JsonGenerator
272
273
Configurable JSON generator for customizing serialization behavior.
274
275
```groovy { .api }
276
class JsonGenerator {
277
static interface Converter {
278
boolean handles(Class<?> type)
279
Object convert(Object value, String key)
280
}
281
282
static class Options {
283
Options addConverter(Converter converter)
284
Options excludeNulls()
285
Options excludeFieldsByName(String... fieldNames)
286
Options excludeFieldsByType(Class... types)
287
Options dateFormat(String format)
288
Options dateFormat(String format, Locale locale)
289
Options timezone(String timezone)
290
Options disableUnicodeEscaping()
291
}
292
293
static Options options()
294
String toJson(Object object)
295
String toJson(Object object, Options options)
296
}
297
```
298
299
Usage example:
300
```groovy
301
import groovy.json.JsonGenerator
302
303
def generator = new JsonGenerator.Options()
304
.excludeNulls()
305
.dateFormat('yyyy-MM-dd')
306
.build()
307
308
def person = [
309
name: 'John',
310
age: 30,
311
birthDate: new Date(),
312
spouse: null // Will be excluded due to excludeNulls()
313
]
314
315
def json = generator.toJson(person)
316
println json
317
```
318
319
## Error Handling
320
321
Common JSON processing exceptions and error patterns:
322
323
```groovy
324
import groovy.json.JsonException
325
import groovy.json.JsonSlurper
326
327
try {
328
def slurper = new JsonSlurper()
329
def result = slurper.parseText('{"invalid": json}') // Invalid JSON
330
} catch (JsonException e) {
331
println "JSON parsing error: ${e.message}"
332
}
333
334
// Handle missing properties gracefully
335
def json = '{"name": "John"}'
336
def slurper = new JsonSlurper()
337
def person = slurper.parseText(json)
338
def age = person.age ?: 0 // Default to 0 if age is missing
339
```
340
341
## Advanced Usage Patterns
342
343
### Custom Object Serialization
344
345
```groovy
346
import groovy.json.JsonBuilder
347
import groovy.transform.ToString
348
349
@ToString
350
class Person {
351
String name
352
int age
353
Date birthDate
354
355
// Custom JSON representation
356
def toJsonMap() {
357
[
358
name: name,
359
age: age,
360
birthYear: birthDate.year + 1900
361
]
362
}
363
}
364
365
def person = new Person(name: 'John', age: 30, birthDate: new Date())
366
def builder = new JsonBuilder(person.toJsonMap())
367
println builder.toPrettyString()
368
```
369
370
### Working with Large JSON Files
371
372
```groovy
373
import groovy.json.JsonSlurper
374
import groovy.json.StreamingJsonBuilder
375
376
// Parse large JSON file efficiently
377
def slurper = new JsonSlurper()
378
new File('large-data.json').withInputStream { stream ->
379
def data = slurper.parse(stream)
380
// Process data in chunks
381
data.records.each { record ->
382
// Process individual records
383
processRecord(record)
384
}
385
}
386
387
// Generate large JSON files efficiently
388
new File('output.json').withWriter { writer ->
389
def builder = new StreamingJsonBuilder(writer)
390
builder {
391
records(largeDataSet) { record ->
392
id record.id
393
name record.name
394
// Include only necessary fields
395
}
396
}
397
}
398
```