0
# JSON Processing
1
2
Comprehensive JSON utilities through the `JSONUtil` class, providing parsing, generation, and manipulation operations with `JSONObject`, `JSONArray`, and `JSONPath` support.
3
4
## Import
5
6
```java
7
import cn.hutool.json.JSONUtil;
8
import cn.hutool.json.JSONObject;
9
import cn.hutool.json.JSONArray;
10
import cn.hutool.json.JSONPath;
11
```
12
13
## JSON Creation
14
15
### Creating JSON Objects
16
17
```java { .api }
18
// Create empty JSON objects
19
public static JSONObject createObj();
20
public static JSONArray createArray();
21
22
// Create from existing data
23
public static JSONObject createObj(Object... keysAndValues);
24
```
25
26
**Usage Examples:**
27
28
```java
29
// Create empty objects
30
JSONObject obj = JSONUtil.createObj();
31
JSONArray arr = JSONUtil.createArray();
32
33
// Create with initial data
34
JSONObject user = JSONUtil.createObj()
35
.put("id", 1)
36
.put("name", "John Doe")
37
.put("email", "john@example.com")
38
.put("active", true);
39
40
// Create from key-value pairs
41
JSONObject config = JSONUtil.createObj(
42
"timeout", 5000,
43
"retries", 3,
44
"debug", false
45
);
46
```
47
48
## JSON Parsing
49
50
### Parse from String
51
52
```java { .api }
53
// Parse JSON objects
54
public static JSONObject parseObj(String jsonStr);
55
public static JSONObject parseObj(Object obj);
56
57
// Parse JSON arrays
58
public static JSONArray parseArray(String jsonStr);
59
public static JSONArray parseArray(Object obj);
60
61
// Generic parsing
62
public static Object parse(String jsonStr);
63
public static Object parse(Object obj);
64
```
65
66
### Parse from Files and Streams
67
68
```java { .api }
69
// Parse from file
70
public static JSONObject readJSONObject(File file, Charset charset);
71
public static JSONArray readJSONArray(File file, Charset charset);
72
73
// Parse from InputStream
74
public static JSONObject readJSONObject(InputStream inputStream, Charset charset);
75
public static JSONArray readJSONArray(InputStream inputStream, Charset charset);
76
```
77
78
**Usage Examples:**
79
80
```java
81
// Parse JSON string
82
String jsonStr = "{\"name\":\"John\",\"age\":30,\"skills\":[\"Java\",\"Python\"]}";
83
JSONObject user = JSONUtil.parseObj(jsonStr);
84
85
// Parse array
86
String arrayStr = "[{\"id\":1,\"name\":\"Alice\"},{\"id\":2,\"name\":\"Bob\"}]";
87
JSONArray users = JSONUtil.parseArray(arrayStr);
88
89
// Parse from file
90
JSONObject config = JSONUtil.readJSONObject(new File("config.json"), CharsetUtil.UTF_8);
91
```
92
93
## JSON Object Operations
94
95
### JSONObject Class
96
97
```java { .api }
98
public class JSONObject extends LinkedHashMap<String, Object> {
99
// Creation
100
public JSONObject();
101
public JSONObject(String jsonStr);
102
public JSONObject(Object bean);
103
104
// Value operations
105
public JSONObject put(String key, Object value);
106
public JSONObject putOpt(String key, Object value);
107
public JSONObject putAll(Map<String, Object> map);
108
109
// Get operations with type conversion
110
public Object get(String key);
111
public <T> T get(String key, Class<T> type);
112
public String getStr(String key);
113
public Integer getInt(String key);
114
public Long getLong(String key);
115
public Double getDouble(String key);
116
public Boolean getBool(String key);
117
public Date getDate(String key);
118
public JSONObject getJSONObject(String key);
119
public JSONArray getJSONArray(String key);
120
121
// Safe get operations with defaults
122
public String getStr(String key, String defaultValue);
123
public Integer getInt(String key, Integer defaultValue);
124
public Long getLong(String key, Long defaultValue);
125
public Double getDouble(String key, Double defaultValue);
126
public Boolean getBool(String key, Boolean defaultValue);
127
128
// Utility methods
129
public Set<String> keySet();
130
public Collection<Object> values();
131
public boolean containsKey(String key);
132
public boolean isEmpty();
133
public int size();
134
public JSONObject remove(String key);
135
136
// Conversion
137
public String toString();
138
public String toJSONString(int indentFactor);
139
public <T> T toBean(Class<T> beanClass);
140
public Map<String, Object> toMap();
141
}
142
```
143
144
### JSONArray Class
145
146
```java { .api }
147
public class JSONArray extends ArrayList<Object> {
148
// Creation
149
public JSONArray();
150
public JSONArray(String jsonStr);
151
public JSONArray(Collection<?> collection);
152
153
// Add operations
154
public JSONArray add(Object value);
155
public JSONArray addAll(Collection<?> collection);
156
public JSONArray put(int index, Object value);
157
158
// Get operations with type conversion
159
public Object get(int index);
160
public <T> T get(int index, Class<T> type);
161
public String getStr(int index);
162
public Integer getInt(int index);
163
public Long getLong(int index);
164
public Double getDouble(int index);
165
public Boolean getBool(int index);
166
public Date getDate(int index);
167
public JSONObject getJSONObject(int index);
168
public JSONArray getJSONArray(int index);
169
170
// Safe get operations with defaults
171
public String getStr(int index, String defaultValue);
172
public Integer getInt(int index, Integer defaultValue);
173
public Long getLong(int index, Long defaultValue);
174
public Double getDouble(int index, Double defaultValue);
175
public Boolean getBool(int index, Boolean defaultValue);
176
177
// Utility methods
178
public int size();
179
public boolean isEmpty();
180
public JSONArray remove(int index);
181
182
// Conversion
183
public String toString();
184
public String toJSONString(int indentFactor);
185
public <T> List<T> toList(Class<T> elementType);
186
public Object[] toArray();
187
}
188
```
189
190
## JSON Conversion
191
192
### Object to JSON
193
194
```java { .api }
195
// Convert objects to JSON
196
public static JSONObject parseObj(Object obj);
197
public static JSONArray parseArray(Object obj);
198
199
// Convert with custom serialization
200
public static String toJsonStr(Object obj);
201
public static String toJsonPrettyStr(Object obj);
202
```
203
204
### JSON to Object
205
206
```java { .api }
207
// Convert to Java objects
208
public static <T> T toBean(String jsonStr, Class<T> beanType);
209
public static <T> T toBean(JSONObject json, Class<T> beanType);
210
211
// Convert to collections
212
public static <T> List<T> toList(String jsonStr, Class<T> elementType);
213
public static <T> List<T> toList(JSONArray jsonArray, Class<T> elementType);
214
215
// Convert to maps
216
public static Map<String, Object> toMap(String jsonStr);
217
```
218
219
**Usage Examples:**
220
221
```java
222
// Object to JSON
223
User user = new User("John", 30, Arrays.asList("Java", "Python"));
224
JSONObject userJson = JSONUtil.parseObj(user);
225
String jsonString = JSONUtil.toJsonStr(user);
226
227
// JSON to Object
228
String userStr = "{\"name\":\"John\",\"age\":30,\"skills\":[\"Java\",\"Python\"]}";
229
User restored = JSONUtil.toBean(userStr, User.class);
230
231
// JSON to List
232
String usersStr = "[{\"name\":\"Alice\"},{\"name\":\"Bob\"}]";
233
List<User> users = JSONUtil.toList(usersStr, User.class);
234
```
235
236
## JSON Path Operations
237
238
### JSONPath Class
239
240
```java { .api }
241
public class JSONPath {
242
// Creation
243
public static JSONPath of(String path);
244
245
// Value extraction
246
public Object getByPath(Object json);
247
public <T> T getByPath(Object json, Class<T> type);
248
249
// Value setting
250
public void setByPath(Object json, Object value);
251
252
// Path utilities
253
public static Object getByPath(Object json, String path);
254
public static <T> T getByPath(Object json, String path, Class<T> type);
255
public static void setByPath(Object json, String path, Object value);
256
}
257
```
258
259
**Usage Examples:**
260
261
```java
262
String jsonStr = """
263
{
264
"users": [
265
{"name": "John", "address": {"city": "New York"}},
266
{"name": "Jane", "address": {"city": "London"}}
267
],
268
"total": 2
269
}
270
""";
271
272
JSONObject json = JSONUtil.parseObj(jsonStr);
273
274
// Extract values using JSON path
275
String firstCity = JSONPath.getByPath(json, "$.users[0].address.city", String.class);
276
// Result: "New York"
277
278
Integer total = JSONPath.getByPath(json, "$.total", Integer.class);
279
// Result: 2
280
281
// Set values using JSON path
282
JSONPath.setByPath(json, "$.users[0].active", true);
283
JSONPath.setByPath(json, "$.lastUpdated", DateUtil.now());
284
```
285
286
## JSON Utilities
287
288
### Formatting and Pretty Printing
289
290
```java { .api }
291
// Format JSON strings
292
public static String formatJsonStr(String jsonStr);
293
public static String formatJsonStr(String jsonStr, int indentFactor);
294
295
// Check if string is valid JSON
296
public static boolean isJson(String str);
297
public static boolean isJsonObj(String str);
298
public static boolean isJsonArray(String str);
299
```
300
301
### JSON Comparison
302
303
```java { .api }
304
// Compare JSON objects
305
public static boolean jsonEquals(String json1, String json2);
306
```
307
308
**Usage Examples:**
309
310
```java
311
// Pretty print JSON
312
String compactJson = "{\"name\":\"John\",\"age\":30}";
313
String prettyJson = JSONUtil.formatJsonStr(compactJson);
314
/*
315
{
316
"name": "John",
317
"age": 30
318
}
319
*/
320
321
// Validate JSON
322
boolean isValid = JSONUtil.isJson("{\"valid\": true}"); // true
323
boolean isInvalid = JSONUtil.isJson("{invalid json}"); // false
324
325
// Compare JSON
326
boolean same = JSONUtil.jsonEquals(
327
"{\"a\":1,\"b\":2}",
328
"{\"b\":2,\"a\":1}" // true - order doesn't matter
329
);
330
```
331
332
## Configuration and Customization
333
334
### JSON Configuration
335
336
```java { .api }
337
// Custom JSON configuration
338
public static void setDateFormat(String dateFormat);
339
public static void setIgnoreNullValue(boolean ignoreNullValue);
340
```
341
342
### Bean Conversion Options
343
344
When converting between JSON and Java objects, Hutool provides options for:
345
346
- **Date Format**: Customize how dates are serialized/deserialized
347
- **Null Handling**: Control whether null values are included
348
- **Property Naming**: Configure property name conversion strategies
349
- **Type Conversion**: Handle custom type conversions
350
351
**Usage Examples:**
352
353
```java
354
// Configure date format for JSON serialization
355
JSONUtil.setDateFormat("yyyy-MM-dd HH:mm:ss");
356
357
// Create object with date
358
User user = new User();
359
user.setCreatedAt(new Date());
360
361
// Convert to JSON (will use configured date format)
362
String json = JSONUtil.toJsonStr(user);
363
364
// Configure to ignore null values
365
JSONUtil.setIgnoreNullValue(true);
366
JSONObject obj = JSONUtil.createObj()
367
.put("name", "John")
368
.put("email", null); // This will be excluded from JSON string
369
```
370
371
## Error Handling
372
373
JSON operations handle malformed JSON gracefully:
374
375
- **Parsing Errors**: Invalid JSON strings throw `JSONException`
376
- **Type Conversion**: Safe type conversion methods return defaults for incompatible types
377
- **Path Errors**: JSONPath operations return null for non-existent paths
378
- **Null Safety**: All operations handle null inputs appropriately
379
380
The JSON utilities provide a complete solution for working with JSON data in Java applications, with support for complex nested structures, type-safe conversions, and JSONPath queries.