0
# Core JSON Operations
1
2
This document covers the essential JSON operations using JSONValue, JSONObject, and JSONArray - the primary classes for JSON parsing, creation, serialization, and basic manipulation.
3
4
## JSONValue - Primary Entry Point
5
6
JSONValue provides static utility methods for all common JSON operations. It serves as the main entry point for parsing, serialization, and validation.
7
8
### Parsing Methods
9
10
#### Basic Parsing (Permissive Mode)
11
12
```java { .api }
13
public static Object parse(String s);
14
public static Object parse(Reader in);
15
public static Object parse(InputStream in);
16
public static Object parse(byte[] in);
17
```
18
19
Parse JSON from various input sources using permissive mode (fastest, handles malformed JSON gracefully).
20
21
```java
22
// Parse JSON string to generic Object
23
Object result = JSONValue.parse("{\"name\": \"John\", \"age\": 30}");
24
25
// Parse from Reader
26
Reader reader = new StringReader("{\"active\": true}");
27
Object data = JSONValue.parse(reader);
28
29
// Parse from byte array
30
byte[] jsonBytes = "{\"count\": 42}".getBytes();
31
Object parsed = JSONValue.parse(jsonBytes);
32
```
33
34
#### Type-Safe Parsing
35
36
```java { .api }
37
public static <T> T parse(String in, Class<T> mapTo);
38
public static <T> T parse(Reader in, Class<T> mapTo);
39
public static <T> T parse(InputStream in, Class<T> mapTo);
40
public static <T> T parse(byte[] in, Class<T> mapTo);
41
```
42
43
Parse JSON directly to specific Java types.
44
45
```java
46
// Parse to JSONObject
47
JSONObject obj = JSONValue.parse("{\"name\": \"Alice\"}", JSONObject.class);
48
49
// Parse to custom class
50
MyUser user = JSONValue.parse(jsonString, MyUser.class);
51
52
// Parse from InputStream to specific type
53
InputStream stream = new FileInputStream("data.json");
54
MyData data = JSONValue.parse(stream, MyData.class);
55
```
56
57
#### Update Existing Objects
58
59
```java { .api }
60
public static <T> T parse(String in, T toUpdate);
61
public static <T> T parse(Reader in, T toUpdate);
62
public static <T> T parse(InputStream in, T toUpdate);
63
```
64
65
Parse JSON and update fields in existing object instances.
66
67
```java
68
MyUser existingUser = new MyUser();
69
existingUser.setId(123);
70
71
// Parse JSON and update existing object (preserves existing fields not in JSON)
72
JSONValue.parse("{\"name\": \"Updated Name\"}", existingUser);
73
```
74
75
#### Exception-Throwing Parsing
76
77
```java { .api }
78
public static Object parseWithException(String input) throws ParseException;
79
public static Object parseWithException(Reader in) throws IOException, ParseException;
80
public static Object parseWithException(InputStream in) throws IOException, ParseException;
81
public static Object parseWithException(byte[] in) throws IOException, ParseException;
82
public static <T> T parseWithException(String in, Class<T> mapTo) throws ParseException;
83
```
84
85
Parse with explicit exception throwing instead of returning null on error.
86
87
#### Strict RFC4627 Parsing
88
89
```java { .api }
90
public static Object parseStrict(String s) throws ParseException;
91
public static Object parseStrict(Reader in) throws IOException, ParseException;
92
```
93
94
Parse using strict RFC4627 compliance (rejects malformed JSON).
95
96
#### Order-Preserving Parsing
97
98
```java { .api }
99
public static Object parseKeepingOrder(String in);
100
public static Object parseKeepingOrder(Reader in);
101
```
102
103
Parse JSON while preserving the order of object fields.
104
105
### Serialization Methods
106
107
```java { .api }
108
public static String toJSONString(Object value);
109
public static String toJSONString(Object value, JSONStyle compression);
110
public static void writeJSONString(Object value, Appendable out) throws IOException;
111
public static void writeJSONString(Object value, Appendable out, JSONStyle compression) throws IOException;
112
```
113
114
Convert Java objects to JSON strings or write to streams.
115
116
```java
117
Object data = Map.of("name", "John", "age", 30);
118
119
// Basic serialization
120
String json = JSONValue.toJSONString(data);
121
122
// Serialization with compression style
123
String compressed = JSONValue.toJSONString(data, JSONStyle.MAX_COMPRESS);
124
125
// Write to StringBuilder/Writer
126
StringBuilder sb = new StringBuilder();
127
JSONValue.writeJSONString(data, sb);
128
129
// Write to file
130
FileWriter writer = new FileWriter("output.json");
131
JSONValue.writeJSONString(data, writer, JSONStyle.NO_COMPRESS);
132
writer.close();
133
```
134
135
### Validation Methods
136
137
```java { .api }
138
public static boolean isValidJson(String s);
139
public static boolean isValidJson(Reader in) throws IOException;
140
public static boolean isValidJsonStrict(String s);
141
public static boolean isValidJsonStrict(Reader in) throws IOException;
142
```
143
144
Validate JSON without parsing to objects.
145
146
```java
147
// Permissive validation
148
boolean valid1 = JSONValue.isValidJson("{name: 'John'}"); // true (allows unquoted keys)
149
150
// Strict validation
151
boolean valid2 = JSONValue.isValidJsonStrict("{name: 'John'}"); // false (requires quoted keys)
152
boolean valid3 = JSONValue.isValidJsonStrict("{\"name\": \"John\"}"); // true
153
```
154
155
### Utility Methods
156
157
```java { .api }
158
public static String compress(String input);
159
public static String compress(String input, JSONStyle style);
160
public static String uncompress(String input);
161
public static String escape(String s);
162
public static String escape(String s, JSONStyle compression);
163
public static void escape(String s, Appendable ap);
164
public static void escape(String s, Appendable ap, JSONStyle compression);
165
```
166
167
Utility methods for JSON string manipulation.
168
169
```java
170
// Compress JSON (remove whitespace)
171
String compressed = JSONValue.compress("{ \"name\" : \"John\" }"); // {"name":"John"}
172
173
// Escape special characters
174
String escaped = JSONValue.escape("Text with \"quotes\" and \n newlines");
175
176
// Uncompress (add readable formatting)
177
String readable = JSONValue.uncompress("{\"name\":\"John\"}");
178
```
179
180
### Configuration Methods
181
182
```java { .api }
183
public static <T> void remapField(Class<T> type, String jsonFieldName, String javaFieldName);
184
public static <T> void registerWriter(Class<?> cls, JsonWriterI<T> writer);
185
public static <T> void registerReader(Class<T> type, JsonReaderI<T> mapper);
186
```
187
188
Configure field mapping and custom serialization/deserialization.
189
190
```java
191
// Remap field names between JSON and Java
192
JSONValue.remapField(MyUser.class, "first_name", "firstName");
193
194
// Register custom serializer
195
JSONValue.registerWriter(LocalDate.class, new DateWriter());
196
197
// Register custom deserializer
198
JSONValue.registerReader(LocalDate.class, new DateReader());
199
```
200
201
## JSONObject - Object Manipulation
202
203
JSONObject extends HashMap<String, Object> and implements JSON-aware interfaces for object manipulation.
204
205
### Constructors
206
207
```java { .api }
208
public JSONObject();
209
public JSONObject(int initialCapacity);
210
public JSONObject(Map<String, ?> map);
211
```
212
213
### Fluent API Methods
214
215
```java { .api }
216
public JSONObject appendField(String fieldName, Object fieldValue);
217
```
218
219
Add fields using fluent API pattern.
220
221
```java
222
JSONObject user = new JSONObject()
223
.appendField("name", "Alice")
224
.appendField("age", 25)
225
.appendField("active", true)
226
.appendField("roles", Arrays.asList("admin", "user"));
227
```
228
229
### Type-Safe Getters
230
231
```java { .api }
232
public String getAsString(String key);
233
public Number getAsNumber(String key);
234
```
235
236
Extract values with automatic type conversion.
237
238
```java
239
JSONObject obj = new JSONObject()
240
.appendField("name", "John")
241
.appendField("age", 30)
242
.appendField("score", 95.5);
243
244
String name = obj.getAsString("name"); // "John"
245
Number age = obj.getAsNumber("age"); // 30
246
Number score = obj.getAsNumber("score"); // 95.5
247
248
// Safe conversion - returns null if key doesn't exist or cannot convert
249
String missing = obj.getAsString("missing"); // null
250
Number invalid = obj.getAsNumber("name"); // null (can't convert "John" to number)
251
```
252
253
### Merging Operations
254
255
```java { .api }
256
public void merge(Object o2);
257
public void merge(Object o2, boolean overwrite);
258
```
259
260
Merge with other objects or JSONObjects.
261
262
```java
263
JSONObject base = new JSONObject()
264
.appendField("name", "Alice")
265
.appendField("age", 25);
266
267
JSONObject update = new JSONObject()
268
.appendField("age", 26)
269
.appendField("city", "New York");
270
271
// Merge with overwrite (default)
272
base.merge(update);
273
// Result: {"name": "Alice", "age": 26, "city": "New York"}
274
275
// Merge without overwriting existing fields
276
JSONObject base2 = new JSONObject()
277
.appendField("name", "Bob")
278
.appendField("age", 30);
279
280
base2.merge(update, false);
281
// Result: {"name": "Bob", "age": 30, "city": "New York"} (age not overwritten)
282
```
283
284
### Serialization Methods
285
286
```java { .api }
287
public String toJSONString();
288
public String toJSONString(JSONStyle compression);
289
public String toString(JSONStyle compression);
290
public void writeJSONString(Appendable out) throws IOException;
291
public void writeJSONString(Appendable out, JSONStyle compression) throws IOException;
292
```
293
294
Convert to JSON strings or write to streams.
295
296
```java
297
JSONObject obj = new JSONObject()
298
.appendField("name", "Test")
299
.appendField("value", 42);
300
301
// Basic serialization
302
String json = obj.toJSONString(); // {"name":"Test","value":42}
303
304
// With formatting
305
String formatted = obj.toJSONString(JSONStyle.NO_COMPRESS);
306
307
// Write to stream
308
StringBuilder sb = new StringBuilder();
309
obj.writeJSONString(sb, JSONStyle.MAX_COMPRESS);
310
```
311
312
### Static Utility Methods
313
314
```java { .api }
315
public static String escape(String s);
316
public static String toJSONString(Map<String, ? extends Object> map);
317
public static String toJSONString(Map<String, ? extends Object> map, JSONStyle compression);
318
public static void writeJSON(Map<String, ? extends Object> map, Appendable out) throws IOException;
319
public static void writeJSON(Map<String, ? extends Object> map, Appendable out, JSONStyle compression) throws IOException;
320
public static void writeJSONKV(String key, Object value, Appendable out, JSONStyle compression) throws IOException;
321
```
322
323
Static methods for working with Maps and individual key-value pairs.
324
325
## JSONArray - Array Manipulation
326
327
JSONArray extends ArrayList<Object> and implements JSON-aware interfaces for array manipulation.
328
329
### Constructors
330
331
```java { .api }
332
public JSONArray();
333
public JSONArray(int initialCapacity);
334
```
335
336
### Fluent API Methods
337
338
```java { .api }
339
public JSONArray appendElement(Object element);
340
```
341
342
Add elements using fluent API pattern.
343
344
```java
345
JSONArray numbers = new JSONArray()
346
.appendElement(1)
347
.appendElement(2)
348
.appendElement(3);
349
350
JSONArray mixed = new JSONArray()
351
.appendElement("string")
352
.appendElement(42)
353
.appendElement(true)
354
.appendElement(new JSONObject().appendField("nested", "object"));
355
```
356
357
### Merging Operations
358
359
```java { .api }
360
public void merge(Object o2);
361
```
362
363
Merge with other arrays or objects.
364
365
```java
366
JSONArray arr1 = new JSONArray()
367
.appendElement("a")
368
.appendElement("b");
369
370
JSONArray arr2 = new JSONArray()
371
.appendElement("c")
372
.appendElement("d");
373
374
// Merge arrays (concatenation)
375
arr1.merge(arr2);
376
// Result: ["a", "b", "c", "d"]
377
378
// Merge with object (adds object as element)
379
JSONObject obj = new JSONObject().appendField("key", "value");
380
arr1.merge(obj);
381
// Result: ["a", "b", "c", "d", {"key": "value"}]
382
```
383
384
### Serialization Methods
385
386
```java { .api }
387
public String toJSONString();
388
public String toJSONString(JSONStyle compression);
389
public String toString(JSONStyle compression);
390
public void writeJSONString(Appendable out) throws IOException;
391
public void writeJSONString(Appendable out, JSONStyle compression) throws IOException;
392
```
393
394
Convert to JSON strings or write to streams.
395
396
```java
397
JSONArray arr = new JSONArray()
398
.appendElement("item1")
399
.appendElement(42)
400
.appendElement(true);
401
402
// Basic serialization
403
String json = arr.toJSONString(); // ["item1",42,true]
404
405
// With formatting
406
String formatted = arr.toJSONString(JSONStyle.NO_COMPRESS);
407
408
// Write to stream
409
FileWriter writer = new FileWriter("array.json");
410
arr.writeJSONString(writer, JSONStyle.LT_COMPRESS);
411
writer.close();
412
```
413
414
### Static Utility Methods
415
416
```java { .api }
417
public static String toJSONString(List<? extends Object> list);
418
public static String toJSONString(List<? extends Object> list, JSONStyle compression);
419
public static void writeJSONString(List<? extends Object> list, Appendable out) throws IOException;
420
public static void writeJSONString(Iterable<? extends Object> list, Appendable out, JSONStyle compression) throws IOException;
421
```
422
423
Static methods for serializing any List or Iterable to JSON.
424
425
```java
426
List<String> stringList = Arrays.asList("apple", "banana", "cherry");
427
String json = JSONArray.toJSONString(stringList); // ["apple","banana","cherry"]
428
429
// Write any Iterable to stream
430
Set<Integer> numberSet = Set.of(1, 2, 3);
431
StringBuilder sb = new StringBuilder();
432
JSONArray.writeJSONString(numberSet, sb, JSONStyle.MAX_COMPRESS);
433
```
434
435
## Usage Examples
436
437
### Complete CRUD Operations
438
439
```java
440
// Create
441
JSONObject user = new JSONObject()
442
.appendField("id", 1)
443
.appendField("name", "John Doe")
444
.appendField("email", "john@example.com")
445
.appendField("active", true);
446
447
// Read - parse from JSON string
448
String jsonString = "{\"id\":1,\"name\":\"John Doe\",\"email\":\"john@example.com\",\"active\":true}";
449
JSONObject parsed = JSONValue.parse(jsonString, JSONObject.class);
450
451
// Update - modify existing object
452
parsed.put("name", "John Smith");
453
parsed.appendField("lastLogin", "2023-10-15");
454
455
// Delete - remove field
456
parsed.remove("email");
457
458
// Serialize back to JSON
459
String updated = JSONValue.toJSONString(parsed);
460
```
461
462
### Working with Nested Structures
463
464
```java
465
// Create nested structure
466
JSONObject address = new JSONObject()
467
.appendField("street", "123 Main St")
468
.appendField("city", "Springfield")
469
.appendField("zipCode", "12345");
470
471
JSONArray phoneNumbers = new JSONArray()
472
.appendElement("555-1234")
473
.appendElement("555-5678");
474
475
JSONObject person = new JSONObject()
476
.appendField("name", "Alice Johnson")
477
.appendField("address", address)
478
.appendField("phoneNumbers", phoneNumbers);
479
480
// Access nested data
481
JSONObject parsedPerson = JSONValue.parse(person.toJSONString(), JSONObject.class);
482
JSONObject personAddress = (JSONObject) parsedPerson.get("address");
483
String city = personAddress.getAsString("city"); // "Springfield"
484
485
JSONArray phones = (JSONArray) parsedPerson.get("phoneNumbers");
486
String firstPhone = (String) phones.get(0); // "555-1234"
487
```
488
489
### Batch Processing
490
491
```java
492
// Process multiple JSON objects
493
String[] jsonStrings = {
494
"{\"name\": \"Alice\", \"score\": 95}",
495
"{\"name\": \"Bob\", \"score\": 87}",
496
"{\"name\": \"Charlie\", \"score\": 92}"
497
};
498
499
JSONArray results = new JSONArray();
500
for (String json : jsonStrings) {
501
JSONObject person = JSONValue.parse(json, JSONObject.class);
502
Number score = person.getAsNumber("score");
503
if (score != null && score.intValue() > 90) {
504
results.appendElement(person);
505
}
506
}
507
508
// Serialize high scorers
509
String highScorers = JSONValue.toJSONString(results);
510
```