0
# JSON Parsing
1
2
High-performance JSON parsing with multiple parser implementations optimized for different scenarios, from small payloads to large streaming documents.
3
4
## Capabilities
5
6
### JsonSlurper
7
8
The primary JSON parsing class offering multiple parser implementations with configuration options for performance and feature trade-offs.
9
10
```java { .api }
11
/**
12
* High-performance JSON parser with configurable parsing strategies
13
*/
14
public class JsonSlurper {
15
/** Default constructor using INDEX_OVERLAY parser */
16
public JsonSlurper();
17
18
/** Parse JSON from string text */
19
public Object parseText(String text);
20
21
/** Parse JSON from Reader */
22
public Object parse(Reader reader);
23
24
/** Parse JSON from InputStream */
25
public Object parse(InputStream inputStream);
26
public Object parse(InputStream inputStream, String charset);
27
28
/** Parse JSON from byte array */
29
public Object parse(byte[] bytes);
30
public Object parse(byte[] bytes, String charset);
31
32
/** Parse JSON from character array */
33
public Object parse(char[] chars);
34
35
/** Parse JSON from File */
36
public Object parse(Path path) throws IOException;
37
public Object parse(Path path, String charset) throws IOException;
38
public Object parse(File file);
39
public Object parse(File file, String charset);
40
41
/** Parse JSON from URL */
42
public Object parse(URL url);
43
public Object parse(URL url, Map params);
44
public Object parse(Map params, URL url);
45
public Object parse(URL url, String charset);
46
public Object parse(URL url, Map params, String charset);
47
public Object parse(Map params, URL url, String charset);
48
49
/** Configuration methods */
50
public JsonParserType getType();
51
public JsonSlurper setType(JsonParserType type);
52
public int getMaxSizeForInMemory();
53
public JsonSlurper setMaxSizeForInMemory(int maxSizeForInMemory);
54
public boolean isChop();
55
public JsonSlurper setChop(boolean chop);
56
public boolean isLazyChop();
57
public JsonSlurper setLazyChop(boolean lazyChop);
58
public boolean isCheckDates();
59
public JsonSlurper setCheckDates(boolean checkDates);
60
}
61
```
62
63
**Usage Examples:**
64
65
```java
66
import groovy.json.JsonSlurper;
67
import groovy.json.JsonParserType;
68
69
// Basic parsing
70
JsonSlurper jsonSlurper = new JsonSlurper();
71
Object result = jsonSlurper.parseText('{"name":"John","age":30}');
72
73
// Configure parser for large files
74
JsonSlurper largeFileSlurper = new JsonSlurper()
75
.setType(JsonParserType.CHARACTER_SOURCE)
76
.setMaxSizeForInMemory(1024 * 1024); // 1MB threshold
77
78
Object data = largeFileSlurper.parse(new File("large-data.json"));
79
80
// Parse from URL with connection parameters
81
Map<String, String> params = new HashMap<>();
82
params.put("connectTimeout", "5000");
83
params.put("readTimeout", "10000");
84
Object webData = jsonSlurper.parse(params, new URL("https://api.example.com/data"));
85
86
// Relaxed parsing with comments
87
JsonSlurper relaxedSlurper = new JsonSlurper().setType(JsonParserType.LAX);
88
Object result = relaxedSlurper.parseText("""
89
{
90
// This is a comment
91
"name": "John",
92
age: 30 // Unquoted keys allowed
93
}
94
""");
95
```
96
97
### JsonParserType
98
99
Enum defining different parser implementations with varying performance characteristics and feature sets.
100
101
```java { .api }
102
/**
103
* Parser implementation types with different performance/feature trade-offs
104
*/
105
public enum JsonParserType {
106
/** Fastest parser using pointers to original character buffer */
107
INDEX_OVERLAY,
108
109
/** Parser for large files using windowing to manage memory */
110
CHARACTER_SOURCE,
111
112
/** Relaxed parser allowing JavaScript-style comments and unquoted keys */
113
LAX,
114
115
/** Fast basic parser without index overlay optimization */
116
CHAR_BUFFER
117
}
118
```
119
120
**Parser Selection Guide:**
121
- **INDEX_OVERLAY**: Default choice for maximum performance with small to medium JSON documents
122
- **CHARACTER_SOURCE**: Use for large JSON files that exceed available memory
123
- **LAX**: Use when parsing JSON with JavaScript-style comments or unquoted property names
124
- **CHAR_BUFFER**: Alternative fast parser when INDEX_OVERLAY is not suitable
125
126
### JsonSlurperClassic
127
128
Legacy JsonSlurper implementation maintained for compatibility with older Groovy versions. Provides the same parsing interface as JsonSlurper but uses the original implementation.
129
130
```java { .api }
131
/**
132
* Original JsonSlurper implementation for compatibility with older Groovy versions
133
*/
134
public class JsonSlurperClassic {
135
/** Default constructor */
136
public JsonSlurperClassic();
137
138
/** Parse JSON from string text */
139
public Object parseText(String text);
140
141
/** Parse JSON from Reader */
142
public Object parse(Reader reader);
143
144
/** Parse JSON from InputStream */
145
public Object parse(InputStream inputStream);
146
public Object parse(InputStream inputStream, String charset);
147
148
/** Parse JSON from byte array */
149
public Object parse(byte[] bytes);
150
public Object parse(byte[] bytes, String charset);
151
152
/** Parse JSON from character array */
153
public Object parse(char[] chars);
154
155
/** Parse JSON from File */
156
public Object parse(File file);
157
public Object parse(File file, String charset);
158
159
/** Parse JSON from URL */
160
public Object parse(URL url);
161
public Object parse(URL url, String charset);
162
public Object parse(URL url, Map params);
163
public Object parse(URL url, Map params, String charset);
164
public Object parse(Map params, URL url);
165
public Object parse(Map params, URL url, String charset);
166
}
167
```
168
169
**Usage Examples:**
170
171
```java
172
import groovy.json.JsonSlurperClassic;
173
174
// Use for compatibility with legacy code
175
JsonSlurperClassic classicSlurper = new JsonSlurperClassic();
176
Object result = classicSlurper.parseText('{"legacy":"data"}');
177
178
// Same interface as JsonSlurper
179
Object fileData = classicSlurper.parse(new File("legacy-data.json"));
180
Object urlData = classicSlurper.parse(new URL("https://api.legacy.com/data"));
181
```
182
183
### JsonParser Interface
184
185
Core parser interface implemented by JsonSlurper and internal parser implementations for pluggable parsing strategies.
186
187
```java { .api }
188
/**
189
* Core parsing interface for JSON processing implementations
190
*/
191
public interface JsonParser {
192
/** Parse JSON from string */
193
Object parse(String jsonString);
194
195
/** Parse JSON from byte array */
196
Object parse(byte[] bytes);
197
Object parse(byte[] bytes, String charset);
198
199
/** Parse JSON from character data */
200
Object parse(CharSequence charSequence);
201
Object parse(char[] chars);
202
203
/** Parse JSON from streams */
204
Object parse(Reader reader);
205
Object parse(InputStream input);
206
Object parse(InputStream input, String charset);
207
208
/** Parse JSON from file */
209
Object parse(File file, String charset);
210
}
211
```
212
213
**Usage Examples:**
214
215
```java
216
import groovy.json.JsonParser;
217
import groovy.json.JsonSlurper;
218
219
// JsonSlurper implements JsonParser interface
220
JsonParser parser = new JsonSlurper();
221
Object result = parser.parse('{"message":"Hello World"}');
222
223
// Use interface for pluggable parsing strategies
224
public class CustomJsonProcessor {
225
private final JsonParser parser;
226
227
public CustomJsonProcessor(JsonParser parser) {
228
this.parser = parser;
229
}
230
231
public Object processJsonFile(File file) {
232
return parser.parse(file, "UTF-8");
233
}
234
}
235
```
236
237
## Performance Considerations
238
239
### Parser Selection
240
- **Small JSON (< 1KB)**: INDEX_OVERLAY provides optimal performance
241
- **Medium JSON (1KB - 10MB)**: INDEX_OVERLAY with default settings
242
- **Large JSON (> 10MB)**: CHARACTER_SOURCE with appropriate `maxSizeForInMemory`
243
- **JSON with comments**: LAX parser type required
244
245
### Memory Management
246
```java
247
// Configure memory threshold for large file processing
248
JsonSlurper slurper = new JsonSlurper()
249
.setType(JsonParserType.CHARACTER_SOURCE)
250
.setMaxSizeForInMemory(2 * 1024 * 1024); // 2MB threshold
251
```
252
253
### Buffer Optimization
254
```java
255
// Enable buffer chopping for memory efficiency
256
JsonSlurper slurper = new JsonSlurper()
257
.setChop(true) // Enable immediate buffer chopping
258
.setLazyChop(false); // Disable lazy chopping for immediate memory release
259
```
260
261
## Error Handling
262
263
All parsing methods throw `JsonException` for malformed JSON or I/O errors:
264
265
```java
266
try {
267
JsonSlurper slurper = new JsonSlurper();
268
Object result = slurper.parseText("invalid json");
269
} catch (JsonException e) {
270
System.err.println("JSON parsing failed: " + e.getMessage());
271
}
272
```