0
# JSON Processing
1
2
Complete JSON parsing and generation with builder patterns, streaming support, and flexible configuration options for handling various JSON structures.
3
4
## Capabilities
5
6
### JSON Parsing
7
8
Parse JSON text into Groovy data structures with flexible type handling.
9
10
```groovy { .api }
11
/**
12
* Parser for JSON text into Groovy data structures
13
*/
14
class JsonSlurper {
15
/** Create JsonSlurper with default configuration */
16
JsonSlurper()
17
18
/** Parse JSON from string */
19
Object parseText(String text)
20
21
/** Parse JSON from Reader */
22
Object parse(Reader reader)
23
24
/** Parse JSON from File */
25
Object parse(File file)
26
27
/** Parse JSON from InputStream */
28
Object parse(InputStream input)
29
30
/** Parse JSON from URL */
31
Object parse(URL url)
32
33
/** Parse JSON from character array */
34
Object parse(char[] text)
35
36
/** Set the type of JSON parser to use */
37
JsonSlurper setType(JsonParserType type)
38
}
39
40
/**
41
* Enumeration of JSON parser types
42
*/
43
enum JsonParserType {
44
CHARACTER_SOURCE, // Default parser
45
LAX, // Lenient parser allowing comments and unquoted keys
46
INDEX_OVERLAY // Fast parser for large JSON
47
}
48
```
49
50
**Usage Examples:**
51
52
```groovy
53
import groovy.json.JsonSlurper
54
55
// Basic JSON parsing
56
def jsonSlurper = new JsonSlurper()
57
def json = '''
58
{
59
"name": "John Doe",
60
"age": 30,
61
"active": true,
62
"skills": ["Java", "Groovy", "JSON"],
63
"address": {
64
"street": "123 Main St",
65
"city": "Anytown"
66
}
67
}
68
'''
69
70
def result = jsonSlurper.parseText(json)
71
println result.name // "John Doe"
72
println result.age // 30
73
println result.skills[0] // "Java"
74
println result.address.city // "Anytown"
75
76
// Parse from file
77
def jsonFile = new File("data.json")
78
result = jsonSlurper.parse(jsonFile)
79
80
// Parse from URL
81
result = jsonSlurper.parse(new URL("https://api.example.com/data"))
82
83
// Using different parser types
84
def laxSlurper = new JsonSlurper().setType(JsonParserType.LAX)
85
def laxJson = '''
86
{
87
// Comments are allowed in LAX mode
88
name: "unquoted keys allowed",
89
'mixed': "quote styles"
90
}
91
'''
92
result = laxSlurper.parseText(laxJson)
93
```
94
95
### JSON Building
96
97
Create JSON structures using a fluent builder API.
98
99
```groovy { .api }
100
/**
101
* Builder for creating JSON structures
102
*/
103
class JsonBuilder {
104
/** Create empty JsonBuilder */
105
JsonBuilder()
106
107
/** Create JsonBuilder with initial value */
108
JsonBuilder(Object content)
109
110
/** Build JSON using closure */
111
Object call(Closure closure)
112
113
/** Build JSON with named arguments */
114
Object call(Map namedArgs, Closure closure)
115
116
/** Convert to JSON string */
117
String toString()
118
119
/** Convert to pretty-printed JSON string */
120
String toPrettyString()
121
122
/** Get the content as object */
123
Object getContent()
124
}
125
```
126
127
**Usage Examples:**
128
129
```groovy
130
import groovy.json.JsonBuilder
131
132
// Basic JSON building
133
def builder = new JsonBuilder()
134
builder {
135
name "John Doe"
136
age 30
137
active true
138
skills(["Java", "Groovy", "JSON"])
139
address {
140
street "123 Main St"
141
city "Anytown"
142
zipCode 12345
143
}
144
}
145
146
println builder.toString()
147
// Output: {"name":"John Doe","age":30,"active":true,"skills":["Java","Groovy","JSON"],"address":{"street":"123 Main St","city":"Anytown","zipCode":12345}}
148
149
println builder.toPrettyString()
150
// Output: formatted JSON with indentation
151
152
// Building arrays
153
def arrayBuilder = new JsonBuilder()
154
arrayBuilder([
155
[name: "Alice", age: 25],
156
[name: "Bob", age: 30],
157
[name: "Charlie", age: 35]
158
])
159
160
// Conditional building
161
def userBuilder = new JsonBuilder()
162
userBuilder {
163
name "User"
164
if (includeAge) {
165
age 25
166
}
167
if (includeSkills) {
168
skills(["Java", "Groovy"])
169
}
170
}
171
```
172
173
### Streaming JSON Building
174
175
Build JSON with streaming for large datasets.
176
177
```groovy { .api }
178
/**
179
* Streaming JSON builder for large datasets
180
*/
181
class StreamingJsonBuilder {
182
/** Create streaming builder writing to Writer */
183
StreamingJsonBuilder(Writer writer)
184
185
/** Create streaming builder writing to OutputStream */
186
StreamingJsonBuilder(OutputStream output)
187
188
/** Build JSON using closure */
189
Object call(Closure closure)
190
191
/** Build JSON with named arguments */
192
Object call(Map namedArgs, Closure closure)
193
}
194
```
195
196
**Usage Examples:**
197
198
```groovy
199
import groovy.json.StreamingJsonBuilder
200
201
// Stream to file
202
def file = new File("large-data.json")
203
file.withWriter { writer ->
204
def builder = new StreamingJsonBuilder(writer)
205
builder {
206
users(users.collect { user ->
207
[
208
id: user.id,
209
name: user.name,
210
email: user.email
211
]
212
})
213
metadata {
214
total users.size()
215
generated new Date()
216
}
217
}
218
}
219
220
// Stream to HTTP response
221
response.contentType = "application/json"
222
response.withWriter { writer ->
223
def builder = new StreamingJsonBuilder(writer)
224
builder {
225
results data
226
pagination {
227
page currentPage
228
totalPages totalPageCount
229
hasNext currentPage < totalPageCount
230
}
231
}
232
}
233
```
234
235
### JSON Output Utilities
236
237
Utility methods for converting objects to JSON strings.
238
239
```groovy { .api }
240
/**
241
* Utility for converting objects to JSON
242
*/
243
class JsonOutput {
244
/** Convert object to JSON string */
245
static String toJson(Object object)
246
247
/** Convert object to JSON with custom generator */
248
static String toJson(Object object, JsonGenerator generator)
249
250
/** Format JSON string with pretty printing */
251
static String prettyPrint(String jsonPayload)
252
253
/** Check if character needs JSON escaping */
254
static boolean isValidJsonElement(char c)
255
256
/** Escape character for JSON */
257
static String escapeJsonChar(char c)
258
}
259
```
260
261
**Usage Examples:**
262
263
```groovy
264
import groovy.json.JsonOutput
265
266
// Convert objects to JSON
267
def data = [
268
name: "Example",
269
values: [1, 2, 3, 4, 5],
270
enabled: true,
271
config: [timeout: 30, retries: 3]
272
]
273
274
def json = JsonOutput.toJson(data)
275
println json
276
// Output: {"name":"Example","values":[1,2,3,4,5],"enabled":true,"config":{"timeout":30,"retries":3}}
277
278
// Pretty printing
279
def prettyJson = JsonOutput.prettyPrint(json)
280
println prettyJson
281
// Output: formatted with indentation and line breaks
282
283
// Converting various types
284
println JsonOutput.toJson(new Date()) // ISO date string
285
println JsonOutput.toJson([1, 2, 3]) // JSON array
286
println JsonOutput.toJson("Hello\nWorld") // Escaped string
287
```
288
289
### JSON Generator Interface
290
291
Interface for custom JSON generation strategies.
292
293
```groovy { .api }
294
/**
295
* Interface for JSON generation strategies
296
*/
297
interface JsonGenerator {
298
/** Check if generator handles the given type */
299
boolean handles(Class<?> type)
300
301
/** Generate JSON for the given object */
302
Object generate(Object object, String key)
303
}
304
305
/**
306
* Default implementation of JsonGenerator
307
*/
308
class DefaultJsonGenerator implements JsonGenerator {
309
/** Configure options for JSON generation */
310
DefaultJsonGenerator(Map<String, Object> options)
311
312
/** Add converter for specific type */
313
DefaultJsonGenerator addConverter(Class<?> type, Closure converter)
314
315
/** Exclude fields by name */
316
DefaultJsonGenerator excludeFields(String... fields)
317
318
/** Exclude fields by class and field name */
319
DefaultJsonGenerator excludeFields(Class clazz, String... fields)
320
}
321
```
322
323
**Usage Examples:**
324
325
```groovy
326
import groovy.json.JsonGenerator
327
import groovy.json.DefaultJsonGenerator
328
import groovy.json.JsonOutput
329
330
// Custom JSON generator
331
def generator = new DefaultJsonGenerator([
332
dateFormat: "yyyy-MM-dd",
333
prettyPrint: true
334
])
335
336
// Add custom converter for specific type
337
generator.addConverter(java.awt.Point) { point, key ->
338
[x: point.x, y: point.y]
339
}
340
341
// Exclude sensitive fields
342
generator.excludeFields("password", "secret")
343
generator.excludeFields(User, "internalId", "createdAt")
344
345
def user = new User(name: "John", password: "secret123", email: "john@example.com")
346
def json = JsonOutput.toJson(user, generator)
347
// password field will be excluded from output
348
```
349
350
## Exception Handling
351
352
```groovy { .api }
353
/**
354
* Exception thrown during JSON parsing or generation
355
*/
356
class JsonException extends RuntimeException {
357
JsonException(String message)
358
JsonException(String message, Throwable cause)
359
}
360
```
361
362
**Usage Examples:**
363
364
```groovy
365
import groovy.json.JsonSlurper
366
import groovy.json.JsonException
367
368
def jsonSlurper = new JsonSlurper()
369
try {
370
def result = jsonSlurper.parseText('{ invalid json }')
371
} catch (JsonException e) {
372
println "JSON parsing failed: ${e.message}"
373
}
374
```