-
Notifications
You must be signed in to change notification settings - Fork 81
/
Json.java
851 lines (775 loc) · 28.3 KB
/
Json.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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
/*
* The MIT License (MIT)
*
* Copyright 2015-2024 Valentyn Kolesnikov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.underscore;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings({"java:S3740", "java:S3776"})
public final class Json {
private Json() {}
private static final String NULL = "null";
private static final String DIGIT = "digit";
public static class JsonStringBuilder {
public enum Step {
TWO_SPACES(2),
THREE_SPACES(3),
FOUR_SPACES(4),
COMPACT(0),
TABS(1);
private final int indent;
Step(int indent) {
this.indent = indent;
}
public int getIndent() {
return indent;
}
}
private final StringBuilder builder;
private final Step identStep;
private int indent;
public JsonStringBuilder(Step identStep) {
builder = new StringBuilder();
this.identStep = identStep;
}
public JsonStringBuilder() {
builder = new StringBuilder();
this.identStep = Step.TWO_SPACES;
}
public JsonStringBuilder append(final char character) {
builder.append(character);
return this;
}
public JsonStringBuilder append(final String string) {
builder.append(string);
return this;
}
public JsonStringBuilder fillSpaces() {
for (int index = 0; index < indent; index += 1) {
builder.append(identStep == Step.TABS ? '\t' : ' ');
}
return this;
}
public JsonStringBuilder incIndent() {
indent += identStep.getIndent();
return this;
}
public JsonStringBuilder decIndent() {
indent -= identStep.getIndent();
return this;
}
public JsonStringBuilder newLine() {
if (identStep != Step.COMPACT) {
builder.append('\n');
}
return this;
}
public Step getIdentStep() {
return identStep;
}
public String toString() {
return builder.toString();
}
}
public static class JsonArray {
private JsonArray() {}
public static void writeJson(Collection collection, JsonStringBuilder builder) {
if (collection == null) {
builder.append(NULL);
return;
}
Iterator iter = collection.iterator();
builder.append('[').incIndent();
if (!collection.isEmpty()) {
builder.newLine();
}
while (iter.hasNext()) {
Object value = iter.next();
builder.fillSpaces();
JsonValue.writeJson(value, builder);
if (iter.hasNext()) {
builder.append(',').newLine();
}
}
builder.newLine().decIndent().fillSpaces().append(']');
}
public static void writeJson(byte[] array, JsonStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIndent().newLine();
builder.fillSpaces().append(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append(String.valueOf(array[i]));
}
builder.newLine().decIndent().fillSpaces().append(']');
}
}
public static void writeJson(short[] array, JsonStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIndent().newLine();
builder.fillSpaces().append(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append(String.valueOf(array[i]));
}
builder.newLine().decIndent().fillSpaces().append(']');
}
}
public static void writeJson(int[] array, JsonStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIndent().newLine();
builder.fillSpaces().append(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append(String.valueOf(array[i]));
}
builder.newLine().decIndent().fillSpaces().append(']');
}
}
public static void writeJson(long[] array, JsonStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIndent().newLine();
builder.fillSpaces().append(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append(String.valueOf(array[i]));
}
builder.newLine().decIndent().fillSpaces().append(']');
}
}
public static void writeJson(float[] array, JsonStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIndent().newLine();
builder.fillSpaces().append(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append(String.valueOf(array[i]));
}
builder.newLine().decIndent().fillSpaces().append(']');
}
}
public static void writeJson(double[] array, JsonStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIndent().newLine();
builder.fillSpaces().append(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append(String.valueOf(array[i]));
}
builder.newLine().decIndent().fillSpaces().append(']');
}
}
public static void writeJson(boolean[] array, JsonStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIndent().newLine();
builder.fillSpaces().append(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append(String.valueOf(array[i]));
}
builder.newLine().decIndent().fillSpaces().append(']');
}
}
public static void writeJson(char[] array, JsonStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIndent().newLine();
builder.fillSpaces().append('\"').append(String.valueOf(array[0])).append('\"');
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append('"').append(String.valueOf(array[i])).append('"');
}
builder.newLine().decIndent().fillSpaces().append(']');
}
}
public static void writeJson(Object[] array, JsonStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').newLine().incIndent().fillSpaces();
JsonValue.writeJson(array[0], builder);
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
JsonValue.writeJson(array[i], builder);
}
builder.newLine().decIndent().fillSpaces().append(']');
}
}
}
public static class JsonObject {
private JsonObject() {}
public static void writeJson(Map map, JsonStringBuilder builder) {
if (map == null) {
builder.append(NULL);
return;
}
Iterator iter = map.entrySet().iterator();
builder.append('{').incIndent();
if (!map.isEmpty()) {
builder.newLine();
}
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
builder.fillSpaces().append('"');
builder.append(JsonValue.escape(String.valueOf(entry.getKey())));
builder.append('"');
builder.append(':');
if (builder.getIdentStep() != JsonStringBuilder.Step.COMPACT) {
builder.append(' ');
}
JsonValue.writeJson(entry.getValue(), builder);
if (iter.hasNext()) {
builder.append(',').newLine();
}
}
builder.newLine().decIndent().fillSpaces().append('}');
}
}
public static class JsonValue {
private JsonValue() {}
public static void writeJson(Object value, JsonStringBuilder builder) {
if (value == null) {
builder.append(NULL);
} else if (value instanceof String) {
builder.append('"').append(escape((String) value)).append('"');
} else if (value instanceof Double) {
if (((Double) value).isInfinite() || ((Double) value).isNaN()) {
builder.append(NULL);
} else {
builder.append(value.toString());
}
} else if (value instanceof Float) {
if (((Float) value).isInfinite() || ((Float) value).isNaN()) {
builder.append(NULL);
} else {
builder.append(value.toString());
}
} else if (value instanceof Number) {
builder.append(value.toString());
} else if (value instanceof Boolean) {
builder.append(value.toString());
} else if (value instanceof Map) {
JsonObject.writeJson((Map) value, builder);
} else if (value instanceof Collection) {
JsonArray.writeJson((Collection) value, builder);
} else {
doWriteJson(value, builder);
}
}
private static void doWriteJson(Object value, JsonStringBuilder builder) {
if (value instanceof byte[]) {
JsonArray.writeJson((byte[]) value, builder);
} else if (value instanceof short[]) {
JsonArray.writeJson((short[]) value, builder);
} else if (value instanceof int[]) {
JsonArray.writeJson((int[]) value, builder);
} else if (value instanceof long[]) {
JsonArray.writeJson((long[]) value, builder);
} else if (value instanceof float[]) {
JsonArray.writeJson((float[]) value, builder);
} else if (value instanceof double[]) {
JsonArray.writeJson((double[]) value, builder);
} else if (value instanceof boolean[]) {
JsonArray.writeJson((boolean[]) value, builder);
} else if (value instanceof char[]) {
JsonArray.writeJson((char[]) value, builder);
} else if (value instanceof Object[]) {
JsonArray.writeJson((Object[]) value, builder);
} else {
builder.append('"').append(escape(value.toString())).append('"');
}
}
public static String escape(String s) {
if (s == null) {
return null;
}
StringBuilder sb = new StringBuilder();
escape(s, sb);
return sb.toString();
}
private static void escape(String s, StringBuilder sb) {
final int len = s.length();
for (int i = 0; i < len; i++) {
char ch = s.charAt(i);
switch (ch) {
case '"':
sb.append("\\\"");
break;
case '\\':
sb.append("\\\\");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
case '€':
sb.append('€');
break;
default:
if (ch <= '\u001F'
|| ch >= '\u007F' && ch <= '\u009F'
|| ch >= '\u2000' && ch <= '\u20FF') {
String ss = Integer.toHexString(ch);
sb.append("\\u");
for (int k = 0; k < 4 - ss.length(); k++) {
sb.append("0");
}
sb.append(ss.toUpperCase());
} else {
sb.append(ch);
}
break;
}
}
}
}
public static class ParseException extends RuntimeException {
private final int offset;
private final int line;
private final int column;
public ParseException(String message, int offset, int line, int column) {
super(String.format("%s at %d:%d", message, line, column));
this.offset = offset;
this.line = line;
this.column = column;
}
public int getOffset() {
return offset;
}
public int getLine() {
return line;
}
public int getColumn() {
return column;
}
}
public static class JsonParser {
private final String json;
private int index;
private int line;
private int lineOffset;
private int current;
private StringBuilder captureBuffer;
private int captureStart;
public JsonParser(String string) {
this.json = string;
line = 1;
captureStart = -1;
}
public Object parse() {
read();
skipWhiteSpace();
final Object result = readValue();
skipWhiteSpace();
if (!isEndOfText()) {
throw error("Unexpected character");
}
return result;
}
private Object readValue() {
switch (current) {
case 'n':
return readNull();
case 't':
return readTrue();
case 'f':
return readFalse();
case '"':
return readString();
case '[':
return readArray();
case '{':
return readObject();
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return readNumber();
default:
throw expected("value");
}
}
private List<Object> readArray() {
read();
List<Object> array = new ArrayList<>();
skipWhiteSpace();
if (readChar(']')) {
return array;
}
do {
skipWhiteSpace();
array.add(readValue());
skipWhiteSpace();
} while (readChar(','));
if (!readChar(']')) {
throw expected("',' or ']'");
}
return array;
}
private Map<String, Object> readObject() {
read();
Map<String, Object> object = new LinkedHashMap<>();
skipWhiteSpace();
if (readChar('}')) {
return object;
}
do {
skipWhiteSpace();
String name = readName();
skipWhiteSpace();
if (!readChar(':')) {
throw expected("':'");
}
skipWhiteSpace();
object.put(name, readValue());
skipWhiteSpace();
} while (readChar(','));
if (!readChar('}')) {
throw expected("',' or '}'");
}
return object;
}
private String readName() {
if (current != '"') {
throw expected("name");
}
return readString();
}
private String readNull() {
read();
readRequiredChar('u');
readRequiredChar('l');
readRequiredChar('l');
return null;
}
private Boolean readTrue() {
read();
readRequiredChar('r');
readRequiredChar('u');
readRequiredChar('e');
return Boolean.TRUE;
}
private Boolean readFalse() {
read();
readRequiredChar('a');
readRequiredChar('l');
readRequiredChar('s');
readRequiredChar('e');
return Boolean.FALSE;
}
private void readRequiredChar(char ch) {
if (!readChar(ch)) {
throw expected("'" + ch + "'");
}
}
private String readString() {
read();
startCapture();
while (current != '"') {
if (current == '\\') {
pauseCapture();
readEscape();
startCapture();
} else if (current < 0x20) {
throw expected("valid string character");
} else {
read();
}
}
String string = endCapture();
read();
return string;
}
private void readEscape() {
read();
switch (current) {
case '"':
case '/':
case '\\':
captureBuffer.append((char) current);
break;
case 'b':
captureBuffer.append('\b');
break;
case 'f':
captureBuffer.append('\f');
break;
case 'n':
captureBuffer.append('\n');
break;
case 'r':
captureBuffer.append('\r');
break;
case 't':
captureBuffer.append('\t');
break;
case 'u':
char[] hexChars = new char[4];
boolean isHexCharsDigits = true;
for (int i = 0; i < 4; i++) {
read();
if (!isHexDigit()) {
isHexCharsDigits = false;
}
hexChars[i] = (char) current;
}
if (isHexCharsDigits) {
captureBuffer.append((char) Integer.parseInt(new String(hexChars), 16));
} else {
captureBuffer
.append("\\u")
.append(hexChars[0])
.append(hexChars[1])
.append(hexChars[2])
.append(hexChars[3]);
}
break;
default:
throw expected("valid escape sequence");
}
read();
}
private Number readNumber() {
startCapture();
readChar('-');
int firstDigit = current;
if (!readDigit()) {
throw expected(DIGIT);
}
if (firstDigit != '0') {
while (readDigit()) {
// ignored
}
}
readFraction();
readExponent();
final String number = endCapture();
final Number result;
if (number.contains(".") || number.contains("e") || number.contains("E")) {
if (number.length() > 9
|| (number.contains(".") && number.length() - number.lastIndexOf('.') > 2)
&& number.charAt(number.length() - 1) == '0') {
result = new java.math.BigDecimal(number);
} else {
result = Double.valueOf(number);
}
} else {
if (number.length() > 19) {
result = new java.math.BigInteger(number);
} else {
result = Long.valueOf(number);
}
}
return result;
}
private boolean readFraction() {
if (!readChar('.')) {
return false;
}
if (!readDigit()) {
throw expected(DIGIT);
}
while (readDigit()) {
// ignored
}
return true;
}
private boolean readExponent() {
if (!readChar('e') && !readChar('E')) {
return false;
}
if (!readChar('+')) {
readChar('-');
}
if (!readDigit()) {
throw expected(DIGIT);
}
while (readDigit()) {
// ignored
}
return true;
}
private boolean readChar(char ch) {
if (current != ch) {
return false;
}
read();
return true;
}
private boolean readDigit() {
if (!isDigit()) {
return false;
}
read();
return true;
}
private void skipWhiteSpace() {
while (isWhiteSpace()) {
read();
}
}
private void read() {
if (index == json.length()) {
current = -1;
return;
}
if (current == '\n') {
line++;
lineOffset = index;
}
current = json.charAt(index++);
}
private void startCapture() {
if (captureBuffer == null) {
captureBuffer = new StringBuilder();
}
captureStart = index - 1;
}
private void pauseCapture() {
captureBuffer.append(json, captureStart, index - 1);
captureStart = -1;
}
private String endCapture() {
int end = current == -1 ? index : index - 1;
String captured;
if (captureBuffer.length() > 0) {
captureBuffer.append(json, captureStart, end);
captured = captureBuffer.toString();
captureBuffer.setLength(0);
} else {
captured = json.substring(captureStart, end);
}
captureStart = -1;
return captured;
}
private ParseException expected(String expected) {
if (isEndOfText()) {
return error("Unexpected end of input");
}
return error("Expected " + expected);
}
private ParseException error(String message) {
int absIndex = index;
int column = absIndex - lineOffset;
int offset = isEndOfText() ? absIndex : absIndex - 1;
return new ParseException(message, offset, line, column - 1);
}
private boolean isWhiteSpace() {
return current == ' ' || current == '\t' || current == '\n' || current == '\r';
}
private boolean isDigit() {
return current >= '0' && current <= '9';
}
private boolean isHexDigit() {
return isDigit()
|| current >= 'a' && current <= 'f'
|| current >= 'A' && current <= 'F';
}
private boolean isEndOfText() {
return current == -1;
}
}
public static String toJson(Collection collection, JsonStringBuilder.Step identStep) {
final JsonStringBuilder builder = new JsonStringBuilder(identStep);
JsonArray.writeJson(collection, builder);
return builder.toString();
}
public static String toJson(Collection collection) {
return toJson(collection, JsonStringBuilder.Step.TWO_SPACES);
}
public static String toJson(Map map, JsonStringBuilder.Step identStep) {
final JsonStringBuilder builder = new JsonStringBuilder(identStep);
JsonObject.writeJson(map, builder);
return builder.toString();
}
public static String toJson(Map map) {
return toJson(map, JsonStringBuilder.Step.TWO_SPACES);
}
public static Object fromJson(String string) {
return new JsonParser(string).parse();
}
public static String formatJson(String json, JsonStringBuilder.Step identStep) {
Object result = fromJson(json);
if (result instanceof Map) {
return toJson((Map) result, identStep);
}
return toJson((List) result, identStep);
}
public static String formatJson(String json) {
return formatJson(json, JsonStringBuilder.Step.TWO_SPACES);
}
}