/
JSONUtil.java
697 lines (657 loc) · 23.7 KB
/
JSONUtil.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
/*
* Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package org.glassfish.admingui.common.util;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Stack;
/**
* <p>This class provides basic JSON encoding / decoding. It has 2 primary
* methods that are of interest. The first allows you to encode a Java
* Object into JSON. The other allows you to create a Java data
* structure from a JSON String. See:</p>
*
* <ul><li>{@link #jsonToJava(String json)}</li>
* <li>{@link #javaToJSON(Object obj, int depth)}</li></ul>
*/
public class JSONUtil {
private static final String ABORT_PROCESSING = "____EnD___";
private static final String COLON = "____CoLoN___";
private static final String COMMA = "____CoMmA___";
private static final String NULL = "____NuLl___";
/**
* <p> This method returns a Java representation of the given JSON
* String. The Java data structure created will be created using
* Map's, String's, Long's, Float's, Boolean's, and List's as
* specified by the JSON String.</p>
*/
public static Object jsonToJava(String json) {
return replaceSpecial(jsonToJava(new JsonChars(json)));
}
/**
* <p> This method attempts to convert the given Object into a JSON String
* to given depth. If -1 (or lower) is supplied for depth, it will
* walk upto a default depth of 10 levels of the given Object. If 0
* is supplied, it will simply return "". 1 will encode the current
* Object, but no children. 2 will encode the given Object and its
* direct children (if any), and so on.</p>
*
* <p> Strings, Longs, Float, and primitives are considered to not have
* child Objects. Objects which have a public no-argument getXYZ()
* method are considered to be child Objects. Maps and Collections
* will be walked.</p>
*/
public static String javaToJSON(Object obj, int depth) {
if (depth == 0) {
// Make sure we do nothing if told to do nothing...
return "";
} else if (depth == -1) {
// To prevent recursion...
depth = 10;
}
String value = "";
if (obj == null) {
value = "null";
} else if (obj instanceof String) {
String chStr;
int len;
StringCharacterIterator it =
new StringCharacterIterator((String) obj);
char ch = it.first();
StringBuilder builder =
new StringBuilder(((String) obj).length() << 2);
builder.append("\"");
while (ch != CharacterIterator.DONE) {
switch (ch) {
case '\t':
builder.append("\\t");
break;
case '\n':
builder.append("\\n");
break;
case '\r':
builder.append("\\r");
break;
case '\b':
builder.append("\\b");
break;
case '\f':
builder.append("\\f");
break;
case '&':
case '<':
case '>':
case '(':
case ')':
case '{':
case '}':
case ':':
case '/':
case '\\':
case '\'':
case '"':
case '=':
builder.append("\\");
builder.append(ch);
break;
default:
// Check if we should unicode escape this...
if ((ch > 0x7e) || (ch < 0x20)) {
builder.append("\\u");
chStr = Integer.toHexString(ch);
len = chStr.length();
for (int idx=4; idx > len; idx--) {
// Add leading 0's
builder.append('0');
}
builder.append(chStr);
} else {
builder.append(ch);
}
break;
}
ch = it.next();
}
builder.append("\"");
value = builder.toString();
} else if ((obj instanceof Boolean) || (obj instanceof Number)) {
value = obj.toString();
} else if (obj instanceof Object[]) {
StringBuilder builder = new StringBuilder("[");
boolean first = true;
for (Object element : ((Object []) obj)) {
if (first) {
first = false;
} else {
builder.append(',');
}
if (depth == 1) {
// Treat as String, but don't try to go deeper...
builder.append(javaToJSON(element.toString(), 1));
} else {
// Recurse...
builder.append(javaToJSON(element, depth-1));
}
}
builder.append("]");
value = builder.toString();
} else if (obj instanceof Map) {
StringBuilder builder = new StringBuilder("{");
String key;
boolean first = true;
Map map = ((Map) obj);
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
if (first) {
first = false;
} else {
builder.append(',');
}
key = it.next().toString();
builder.append(javaToJSON(key, 1) + ":");
if (depth == 1) {
// Treat as String, but don't try to go deeper...
builder.append(javaToJSON(map.get(key).toString(), 1));
} else {
// Recurse...
builder.append(javaToJSON(map.get(key), depth-1));
}
}
builder.append("}");
value = builder.toString();
} else if (obj instanceof Collection) {
StringBuilder builder = new StringBuilder("[");
boolean first = true;
Iterator it = ((Collection) obj).iterator();
while (it.hasNext()) {
if (first) {
first = false;
} else {
builder.append(',');
}
if (depth == 1) {
// Treat as String, but don't try to go deeper...
builder.append(javaToJSON(it.next().toString(), 1));
} else {
// Recurse...
builder.append(javaToJSON(it.next(), depth-1));
}
}
builder.append("]");
value = builder.toString();
} else {
// Object
StringBuilder builder = new StringBuilder("{");
String methodName;
Object result;
boolean first = true;
Iterator<String> it = getGetters(obj).iterator();
while (it.hasNext()) {
if (first) {
first = false;
} else {
builder.append(',');
}
methodName = it.next();
// Drop "get"...
builder.append(javaToJSON(methodName.substring(3), 1) + ":");
result = invokeGetter(obj, methodName);
if ((result != null) && (depth == 1)) {
// Treat as String, but don't try to go deeper...
builder.append(javaToJSON(result.toString(), 1));
} else {
// Recurse...
builder.append(javaToJSON(result, depth-1));
}
}
builder.append("}");
value = builder.toString();
}
return value;
}
/**
* <p> This method invokes a getter on the given object.</p>
*
* <p> NOTE: I found a VERY similar method defined in IntegrationPoint...
* at least I'm consistent. ;) These should probably be combined.</p>
*/
private static Object invokeGetter(Object obj, String methodName) {
try {
return obj.getClass().getMethod(methodName).invoke(obj);
} catch (Exception ex) {
// Unable to execute it, return null...
return null;
}
}
/**
* <p> This method returns the names of the public no-arg getters on the
* given Object.</p>
*/
private static List<String> getGetters(Object obj) {
List<String> result = new ArrayList<>();
for (Method method : obj.getClass().getMethods()) {
if (method.getName().startsWith("get")
&& ((method.getModifiers() & Modifier.PUBLIC) != 0)
&& (method.getParameterTypes().length == 0)
&& (!method.getName().equals("getClass"))
&& (!method.getReturnType().getName().equals("void"))) {
result.add(method.getName());
}
}
return result;
}
/**
* <p> This is the primary switching method which determines the context
* in which the processing should occur.</p>
*/
private static Object jsonToJava(JsonChars json) {
Object value = null;
while (json.hasNext() && (value == null)) {
char ch = json.next();
switch (ch) {
case '{' :
value = readObject(json);
break;
case '[' :
value = readArray(json);
break;
case '}' :
case ']' :
if (json.isAtContextEnd()) {
// Stop processing
value = ABORT_PROCESSING;
} else {
throw new IllegalArgumentException("Expected '"
+ json.peekContextEnd() + "' but found '"
+ json.current() + "' instead!");
}
break;
case '-' :
case '0' :
case '1' :
case '2' :
case '3' :
case '4' :
case '5' :
case '6' :
case '7' :
case '8' :
case '9' :
value = readNumber(json);
break;
case '\'' :
case '"' :
value = readString(json);
break;
case 'T' :
case 't' :
value = readConstant(json, "true");
break;
case 'F' :
case 'f' :
value = readConstant(json, "false");
break;
case 'N' :
case 'n' :
value = readConstant(json, "null");
break;
case ' ' :
case '\t' :
case '\r' :
case '\n' :
case '\b' :
case '\f' :
// Ignore whitespace
break;
case ':' :
value = COLON;
break;
case ',' :
value = COMMA;
break;
default:
throw new IllegalArgumentException(
"Unexpected char '" + json.current() + "' near: " + json.getContext(30) + "!");
}
}
return value;
}
/**
* <p> This method creates a HashMap to represent the JSON Object.</p>
*/
private static Map<String, Object> readObject(JsonChars json) {
// Save the ending char...
json.pushContextEnd('}');
// Create the Map
Map<String, Object> map = new HashMap<>(10);
Object tmp = null;
Object key = null;
Object value = null;
while (!json.isAtContextEnd()) {
// Get the key
key = replaceSpecial(jsonToJava(json));
if (json.isAtContextEnd()) {
// Abort...
break;
}
if (!(key instanceof String)) {
throw new IllegalArgumentException(
"Object keys must be a String!");
}
// Get the Colon...
if (!(jsonToJava(json).equals(COLON))) {
throw new IllegalArgumentException(
"Object keys must be followed by a colon (:)!");
}
// Get the value
value = replaceSpecial(jsonToJava(json));
// Get the comma between properties (may also be context end)
tmp = jsonToJava(json);
if ( (!(tmp.equals(COMMA))) && !json.isAtContextEnd()) {
throw new IllegalArgumentException(
"Expected comma (,) or end curly brace (}), but found ("
+ tmp + ") instead! Near: (" + json.getContext(30) + ")");
}
// Add the value to the Map...
map.put((String) key, value);
}
// Remove the context end and return
json.popContextEnd();
return map;
}
/**
* <p> This function will process a JSON string and convert it into
* an array.</p>
*/
private static List<Object> readArray(JsonChars json) {
// Save the ending char...
json.pushContextEnd(']');
// Create the List
List<Object> list = new ArrayList<>(10);
Object tmp = null;
Object value = null;
while (!json.isAtContextEnd()) {
// Get the value
value = replaceSpecial(jsonToJava(json));
if (!json.isAtContextEnd()) {
// Get the comma between properties (may also be context end)
tmp = jsonToJava(json);
if (( !(tmp.equals(COMMA))) && !json.isAtContextEnd()) {
throw new IllegalArgumentException(
"Expected comma (,) or end curly brace (}), but found ("
+ tmp + ") instead!");
}
}
// Add the value to the List...
if ((value == null) || ( !(value.equals(ABORT_PROCESSING)))) {
list.add(value);
}
}
// Remove the context end and return
json.popContextEnd();
return list;
}
/**
* <p> This function reads a String and returns it.</p>
*/
private static String readString(JsonChars json) {
// Save the ending char...
json.pushContextEnd(json.current());
// Build the String...
StringBuilder builder = new StringBuilder();
char ch = json.next();
while (!json.isAtContextEnd()) {
if (ch == '\\') {
ch = json.next();
switch (ch) {
case 'b' :
ch = '\b';
break;
case 'f' :
ch = '\f';
break;
case 'n' :
ch = '\n';
break;
case 'r' :
ch = '\r';
break;
case 't' :
ch = '\t';
break;
case 'u' :
// Handle unicode characters
builder.appendCodePoint(Integer.parseInt(""
+ json.next() + json.next()
+ json.next() + json.next()));
continue;
case '"' :
case '\'' :
case '\\' :
case '/' :
// Just allow this char to be added
break;
default:
// Ignore illegal escape character.
break;
}
}
builder.append(ch);
ch = json.next();
}
// Return the result
json.popContextEnd();
return builder.toString();
}
/**
* <p> Returns either a Float or an Long depending on the data.</p>
*/
private static Object readNumber(JsonChars json) {
StringBuilder builder = new StringBuilder();
char ch = json.current();
if (ch == '-') {
builder.append('-');
ch = json.next();
}
boolean hasDecimal = false;
boolean hasExp = false;
boolean done = false;
while (!done) {
switch (ch) {
case '0' :
case '1' :
case '2' :
case '3' :
case '4' :
case '5' :
case '6' :
case '7' :
case '8' :
case '9' :
builder.append(ch);
break;
case '.' :
if (hasDecimal) {
throw new IllegalArgumentException(
"Error while parsing number! Found multiple decimal points.");
}
hasDecimal = true;
builder.append(ch);
break;
case 'e' :
case 'E' :
// We have an exponent
if (hasExp) {
throw new IllegalArgumentException(
"An attempt was made to parse an Long value, however, it was malformed (had to exponents).");
}
hasExp = true;
builder.append(ch);
ch = json.next();
if ((ch == '-') || (ch == '+')) {
builder.append(ch);
ch = json.next();
}
if ((ch < '0') || (ch > '9')) {
throw new IllegalArgumentException(
"Required a digit after an exponent, however received: '" + ch + "'.");
}
builder.append(ch);
break;
default:
done = true;
continue;
}
try {
ch = json.next();
} catch (IndexOutOfBoundsException ioobe) {
done = true;
}
}
// Numbers don't have an ending delimiter, so we need to push the last
// value back onto the queue
json.unread();
// Return the number...
return (hasDecimal || hasExp) ?
(Object) Float.valueOf(builder.toString()) :
(Object) Long.valueOf(builder.toString());
}
/**
* <p> This method attempts to read a true/false/null value and returns a
* Boolean for true/false values or {@link #NULL} for null values.</p>
*/
private static Object readConstant(JsonChars json, String constant) {
byte[] good = constant.getBytes();
int len = good.length;
char ch;
for (int idx=1; idx<len; idx++) {
ch = json.next();
if (ch != good[idx]) {
throw new IllegalArgumentException(
"Expected constant (" + constant + ")!");
}
}
// We compared successfully...
return constant.equals("null") ? NULL : Boolean.valueOf(constant);
}
static class JsonChars {
private final String string;
private final int len;
private int loc = 0;
private final Stack<Character> endContext = new Stack<>();
/**
* Constructor.
*/
JsonChars(String json) {
string = json;
len = string.length();
}
/**
* Returns the current byte.
*/
char current() {
return string.charAt(loc-1);
}
/**
* Returns the current byte and increments the location by 1.
*/
char next() {
return string.charAt(loc++);
//return (loc<len) ? string.charAt(loc++) : null;
}
/**
* Backs up the iteration 1 character.
*/
void unread() {
loc--;
}
/**
* This function returns a String that represents the content
* around the current position. The <code>width</code> property
* specifies how far before and after the current position that
* should be returned as part of the <code>String</code>.
*/
String getContext(int width) {
int before = loc - width;
if (loc < 0) {
loc = 0;
}
if (before < 0) {
before = 0;
}
int after = loc + width;
if (after > len) {
after = len;
}
return string.substring(before, after - before);
}
/**
* <p>Returns the length of the JSON String.</p>
*/
int getLength() {
return len;
}
/**
* <p>Returns true if there are more characters to be parsed.</p>
*/
boolean hasNext() {
return loc<len;
}
/**
* <p>Returns true if the end of the current context is reached. For
* example if the current context is an Object, the ending for an
* Object is a '}' byte.</p>
*/
boolean isAtContextEnd() {
return !hasNext() || (string.charAt(loc-1) == endContext.peek());
}
void pushContextEnd(char end) {
endContext.push(end);
}
char popContextEnd() {
return endContext.pop();
}
char peekContextEnd() {
return endContext.peek();
}
}
/**
* <p> This method substitutes the special Strings to their intended
* representations (null, ':', and ','). This method does nothing
* except return the given value if the requested value is not a
* "special" value.</p>
*/
private static Object replaceSpecial(Object val) {
if (val instanceof String) {
String strVal = (String) val;
if (COLON.equals(strVal)) {
val = ':';
} else if (COMMA.equals(strVal)) {
val = ',';
} else if (NULL.equals(strVal)) {
val = null;
}
}
return val;
}
}