forked from stleary/JSON-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSONWriter.java
More file actions
1255 lines (1182 loc) · 44.5 KB
/
Copy pathJSONWriter.java
File metadata and controls
1255 lines (1182 loc) · 44.5 KB
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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.json;
/*
Copyright (c) 2006 JSON.org
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 shall be used for Good, not Evil.
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.
*/
import org.json.util.ALStack;
import java.io.Closeable;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* JSONWriter provides a quick and convenient way of producing JSON text.
* The texts produced strictly conform to JSON syntax rules. No whitespace is
* added, so the results are ready for transmission or storage. Each instance of
* JSONWriter can produce one JSON text.
* <p>
* A JSONWriter instance provides a <code>value</code> method for appending
* values to the
* text, and a <code>key</code>
* method for adding keys before values in objects. There are <code>array</code>
* and <code>endArray</code> methods that make and bound array values, and
* <code>object</code> and <code>endObject</code> methods which make and bound
* object values. All of these methods return the JSONWriter instance,
* permitting a cascade style. For example, <pre>
* new JSONWriter(myWriter)
* .object()
* .key("JSON")
* .value("Hello, World!")
* .endObject();</pre> which writes <pre>
* {"JSON":"Hello, World!"}</pre>
* <p>
* The first method called must be <code>array</code> or <code>object</code>.
* There are no methods for adding commas or colons. JSONWriter adds them for
* you. Objects and arrays can be nested arbitrarily deep.
* <p>
* This can sometimes be easier than using a JSONObject to build a string.
* @author JSON.org
* @version 2016-08-04
*/
public class JSONWriter implements Closeable {
private static final int initdepth = 16;
/**
* The comma flag determines if a comma should be output before the next
* value.
*/
private boolean comma;
/**
* The current mode. Values:
* 'a' (array),
* 'd' (done),
* 'i' (initial),
* 'k' (key),
* 'o' (object).
*/
protected char mode;
/**
* The object/array stack, for duplicate key detection.
* Arrays are represented as null elements, while objects are
* represented as sets of key strings.
*/
private final ALStack<Set<String>> stack;
/**
* The writer that will receive the output.
*/
protected final Appendable writer;
/**
* Make a fresh JSONWriter. It can be used to build one JSON text.
*
* @param w the Writer to which JSON content will be written
*/
public JSONWriter(Appendable w) {
this.comma = false;
this.mode = 'i';
this.stack = new ALStack<Set<String>>(initdepth);
this.writer = w;
}
/**
* Prepare for the next value to be written. Append a comma if required,
* assert and advance the mode as needed.
*/
private void prepValue() throws JSONException {
try {
switch (this.mode) {
case 'a':
if (this.comma) {
this.writer.append(',');
}
break;
case 'o':
this.mode = 'k';
break;
default:
throw new JSONException("Value out of sequence.");
}
this.comma = true;
} catch (IOException e) {
throw new JSONException(e);
}
}
/**
* Begin appending a new array. All values until the balancing
* <code>endArray</code> will be appended to this array. The
* <code>endArray</code> method must be called to mark the array's end.
* @return this
* @throws JSONException If the nesting is too deep, or if the object is
* started in the wrong place (for example as a key or after the end of the
* outermost array or object).
*/
public JSONWriter array() throws JSONException {
if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') {
this.push(false);
try {
this.prepValue();
this.writer.append('[');
} catch (IOException e) {
throw new JSONException(e);
}
this.comma = false;
return this;
}
throw new JSONException("Misplaced array.");
}
/**
* End something.
* @param mode Mode
* @param c Closing character
* @return this
* @throws JSONException If unbalanced.
*/
private JSONWriter end(char mode, char c) throws JSONException {
if (this.mode != mode) {
throw new JSONException(mode == 'a'
? "Misplaced endArray."
: "Misplaced endObject.");
}
this.pop(mode);
try {
this.writer.append(c);
} catch (IOException e) {
throw new JSONException(e);
}
this.comma = true;
return this;
}
/**
* End an array. This method most be called to balance calls to
* <code>array</code>.
* @return this
* @throws JSONException If incorrectly nested.
*/
public JSONWriter endArray() throws JSONException {
return this.end('a', ']');
}
/**
* End an object. This method most be called to balance calls to
* <code>object</code>.
* @return this
* @throws JSONException If incorrectly nested.
*/
public JSONWriter endObject() throws JSONException {
return this.end('k', '}');
}
/**
* Append a key. The key will be associated with the next value. In an
* object, every value must be preceded by a key.
* @param string A key string.
* @return this
* @throws JSONException If the key is out of place. For example, keys
* do not belong in arrays or if the key is null.
*/
public JSONWriter key(String string) throws JSONException {
if (string == null) {
throw new JSONException("Null key.");
}
if (this.mode == 'k') {
try {
if(!this.stack.peek().add(string)) {
throw new JSONException("Duplicate key \"" + string + "\"");
}
if (this.comma) {
this.writer.append(',');
}
writeString(string, this.writer).append(':');
this.comma = false;
this.mode = 'o';
return this;
} catch (IOException e) {
throw new JSONException(e);
}
}
throw new JSONException("Misplaced key.");
}
/**
* Begin appending a new object. All keys and values until the balancing
* <code>endObject</code> will be appended to this object. The
* <code>endObject</code> method must be called to mark the object's end.
* @return this
* @throws JSONException If the nesting is too deep, or if the object is
* started in the wrong place (for example as a key or after the end of the
* outermost array or object).
*/
public JSONWriter object() throws JSONException {
if (this.mode == 'i') {
this.mode = 'o';
}
if (this.mode == 'o' || this.mode == 'a') {
try {
this.prepValue();
this.writer.append('{');
} catch (IOException e) {
throw new JSONException(e);
}
this.push(true);
this.comma = false;
return this;
}
throw new JSONException("Misplaced object.");
}
/**
* Pop an array or object scope.
* @param c The scope to close.
* @throws JSONException If nesting is wrong.
*/
private void pop(char c) throws JSONException {
if (this.stack.isEmpty()) {
throw new JSONException("Nesting error.");
}
char m = this.stack.pop() == null ? 'a' : 'k';
if (m != c) {
throw new JSONException("Nesting error.");
}
this.mode = this.stack.isEmpty()
? 'd'
: this.stack.peek() == null
? 'a'
: 'k';
}
/**
* Push an object or array scope.
*
* @param obj {@code true} to indicate an Object, otherwise {@code false}
* to indicate an Array
* @throws JSONException If nesting is too deep.
*/
private void push(boolean obj) throws JSONException {
this.stack.push(obj ? new HashSet<String>() : null);
this.mode = obj ? 'k' : 'a';
}
/**
* Append a <code>null</code> value.
* @return this
* @throws JSONException there was a problem writing the null value
*/
public JSONWriter nullValue() throws JSONException {
this.prepValue();
writeNull(this.writer);
return this;
}
/**
* Append either the value <code>true</code> or the value
* <code>false</code>.
* @param b A boolean.
* @return this
* @throws JSONException there was a problem writing the boolean value
*/
public JSONWriter value(boolean b) throws JSONException {
String string = Boolean.toString(b);
try {
this.prepValue();
this.writer.append(string);
return this;
} catch (IOException e) {
throw new JSONException(e);
}
}
/**
* Append a double value.
* @param d A double.
* @return this
* @throws JSONException If the number is not finite.
*/
public JSONWriter value(double d) throws JSONException {
this.prepValue();
writeDouble(d, this.writer);
return this;
}
/**
* Append a long value.
* @param l A long.
* @return this
* @throws JSONException there was a problem writing the long value
*/
public JSONWriter value(long l) throws JSONException {
String string = Long.toString(l);
try {
this.prepValue();
this.writer.append(string);
return this;
} catch (IOException e) {
throw new JSONException(e);
}
}
/**
* Append an object value.
* @param object The object to appendString. It can be null, or a Boolean, Number,
* String, JSONObject, or JSONArray, or an object that implements JSONString.
* @return this
* @throws JSONException If the value is out of sequence.
*/
public JSONWriter value(Object object) throws JSONException {
this.prepValue();
writeValue(object, this.writer);
return this;
}
/**
* Append a sequence of values into an array.
*
* @param values The objects to appendString. They can be null, or a Boolean, Number,
* String, JSONObject, or JSONArray, or an object that implements JSONString.
* @return this
* @throws JSONException If a value is out of place. For example, a value
* occurs where a key is expected.
*/
public JSONWriter values(Iterable<?> values) throws JSONException {
for(Object obj : values) {
this.prepValue();
writeValue(obj, this.writer);
}
return this;
}
/**
* Append a sequence of keys and values in an object.
* The key will be associated with the corresponding value. In an
* object, every value must be associated with a key.
*
* @param kvPairs The objects to appendString. The values can be null, or a Boolean,
* Number, String, JSONObject, or JSONArray, or an object that implements
* JSONString.
* @return this
* @throws JSONException If a key or value is out of place. For example, keys
* do not belong in arrays or if the key is null.
*/
public JSONWriter entries(Map<?, ?> kvPairs) throws JSONException {
for(Entry<?, ?> entry : kvPairs.entrySet()) {
this.key(String.valueOf(entry.getKey()));
this.prepValue();
writeValue(entry.getValue(), this.writer);
}
return this;
}
/**
* Asserts the JSON writer is finished, and close any underlying
* {@code Closeable} writer.
*
* @throws IOException the writer cannot be closed
*/
@Override
public void close() throws IOException {
if(!this.stack.isEmpty()) {
throw new IOException("JSON stack is not empty");
}
if(writer instanceof Closeable) {
((Closeable)writer).close();
}
}
// -- static writer methods
// 120 spaces, divides by 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, ...
private static final String PADDING_SPACES = makePaddingSpaces();
private static final int PADDING_LENGTH = 120;
private static String makePaddingSpaces() {
char[] padding = new char[PADDING_LENGTH];
Arrays.fill(padding, ' ');
return String.valueOf(padding);
}
/**
* Indent by the given number of spaces.
*
* @param indent
* the number of character to indent.
* @param writer
* the writer.
* @param <T>
* A subtype of {@code Appendable}, returned to the caller
* for chaining purposes
* @return The writer.
* @throws IOException there was a problem writing the indentation
*/
static <T extends Appendable> T indent(int indent, T writer) throws IOException {
while(indent >= PADDING_LENGTH) {
writer.append(PADDING_SPACES);
indent -= PADDING_LENGTH;
}
if(indent > 0) {
writer.append(PADDING_SPACES, 0, indent);
}
return writer;
}
/**
* Write the contents of the Object as JSON text to a writer. For
* compactness, no whitespace is added.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @param value
* The value to be written
* @param writer
* Writes the serialized JSON
* @param <T>
* A subtype of {@code Appendable}, returned to the caller
* for chaining purposes
* @return The writer.
* @throws JSONException there was a problem writing the Object
*/
static <T extends Appendable> T writeValue(Object value, T writer)
throws JSONException {
return writeValue(value, writer, 0, 0);
}
/**
* Write the contents of the Object as JSON text to a writer.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @param value
* The value to be written
* @param writer
* Writes the serialized JSON
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @param indent
* The indention of the top level.
* @param <T>
* A subtype of {@code Appendable}, returned to the caller
* for chaining purposes
* @return The writer.
* @throws JSONException there was a problem writing the Object
*/
static <T extends Appendable> T writeValue(Object value, T writer,
int indentFactor, int indent) throws JSONException {
if ((value == null) || JSONObject.NULL.equals(value)) {
return writeNull(writer);
}
if (value instanceof JSONAppendable) {
return writeJSONAppendable((JSONAppendable) value, writer);
}
if (value instanceof JSONString) {
return writeJSONString((JSONString) value, writer);
}
if (value instanceof JSONObject) {
return writeJSONObject((JSONObject) value, writer, indentFactor, indent);
}
if (value instanceof JSONArray) {
return writeJSONArray((JSONArray) value, writer, indentFactor, indent);
}
if (value instanceof Number) {
return writeNumber((Number) value, writer);
}
if (value instanceof Boolean) {
return writeBoolean((Boolean) value, writer);
}
if (value instanceof CharSequence) {
return writeString((CharSequence) value, writer);
}
if (value instanceof Map) {
return writeMap((Map<?, ?>) value, writer, indentFactor, indent);
}
if (value instanceof Iterable) {
return writeIterable((Iterable<?>) value, writer, indentFactor, indent);
}
if (value.getClass().isArray()) {
return writeArray(value, writer, indentFactor, indent);
}
if (value instanceof Enum<?>) {
return writeEnum((Enum<?>) value, writer);
}
if (JSONObject.objectIsBean(value)) {
return writeBean(value, writer, indentFactor, indent);
}
return writeString(value.toString(), writer);
}
/**
* Write the JSONAppendable as a JSON value to a writer.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @param value
* The JSONString to be written
* @param writer
* Writes the serialized JSON
* @param <T> a subtype of {@code Appendable}, returned to the caller
* for chaining purposes
* @return The writer.
* @throws JSONException there was a problem writing the JSONAppendable
*/
static <T extends Appendable> T writeJSONAppendable(JSONAppendable value,
T writer) throws JSONException {
try {
value.appendJSON(writer);
return writer;
} catch(JSONException e) {
// Propagate directly, because JSONException is a RuntimeException
throw e;
} catch(IOException e) {
throw new JSONException(e);
} catch(RuntimeException e) {
throw new JSONException(e);
}
}
/**
* Write the contents of the JSONString as a JSON value to a writer.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @param value
* The JSONString to be written
* @param writer
* Writes the serialized JSON
* @param <T> a subtype of {@code Appendable}, returned to the caller
* for chaining purposes
* @return The writer.
* @throws JSONException there was a problem writing the JSONString
*/
static <T extends Appendable> T writeJSONString(JSONString value, T writer)
throws JSONException {
try {
String o = value.toJSONString();
if (o != null) {
writer.append(o);
} else {
writeString(value.toString(), writer);
}
return writer;
} catch(JSONException e) {
// Propagate directly, because JSONException is a RuntimeException
throw e;
} catch (IOException e) {
throw new JSONException(e);
} catch (RuntimeException e) {
throw new JSONException(e);
}
}
/**
* Write the contents of the JavaBean as JSON object to a writer.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @param bean
* The bean to be written
* @param writer
* Writes the serialized JSON
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @param indent
* The indention of the top level.
* @param <T>
* A subtype of {@code Appendable}, returned to the caller
* for chaining purposes
* @return The writer.
* @throws JSONException there was a problem writing the bean
*/
static <T extends Appendable> T writeBean(Object bean, T writer,
int indentFactor, int indent) throws JSONException {
try {
final int newindent = indent + indentFactor;
Class<?> klass = bean.getClass();
// If klass is a System class then set includeSuperClass to false.
boolean includeSuperClass = klass.getClassLoader() != null;
Method[] methods = includeSuperClass ? klass.getMethods()
: klass.getDeclaredMethods();
boolean commanate = false;
writer.append('{');
for (int i = 0; i < methods.length; i += 1) {
try {
Method method = methods[i];
if (Modifier.isPublic(method.getModifiers()) &&
!Modifier.isStatic(method.getModifiers()) &&
!method.isSynthetic() &&
(method.getReturnType() != Void.TYPE)) {
String name = method.getName();
String key = JSONObject.keyFromMethodName(name);
if ((key != null)
&& (method.getParameterTypes().length == 0)) {
Object result = method.invoke(bean, (Object[]) null);
if (result != null) {
if (commanate) {
writer.append(',');
}
if (indentFactor > 0) {
writer.append('\n');
}
indent(newindent, writer);
writeString(String.valueOf(key), writer).append(':');
if (indentFactor > 0) {
writer.append(' ');
}
writeValue(result, writer, indentFactor, newindent);
commanate = true;
}
}
}
} catch (Exception ignore) {
}
}
if(commanate) {
if (indentFactor > 0) {
writer.append('\n');
}
indent(indent, writer);
}
writer.append('}');
return writer;
} catch (IOException exception) {
throw new JSONException(exception);
} catch (RuntimeException exception) {
throw new JSONException(exception);
}
}
/**
* Write the contents of the Map as JSON object to a writer.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @param map
* The Map to be written
* @param writer
* Writes the serialized JSON
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @param indent
* The indention of the top level.
* @param <T>
* A subtype of {@code Appendable}, returned to the caller
* for chaining purposes
* @return The writer.
* @throws JSONException there was a problem writing the Map
*/
static <T extends Appendable> T writeMap(Map<?, ?> map, T writer,
int indentFactor, int indent) throws JSONException {
try {
boolean commanate = false;
final int length = map.size();
Iterator<?> keys = map.keySet().iterator();
writer.append('{');
if (length == 1) {
Object key = keys.next();
writeString(String.valueOf(key), writer).append(':');
if (indentFactor > 0) {
writer.append(' ');
}
writeValue(map.get(key), writer, indentFactor, indent);
} else if (length != 0) {
final int newindent = indent + indentFactor;
while (keys.hasNext()) {
Object key = keys.next();
if (commanate) {
writer.append(',');
}
if (indentFactor > 0) {
writer.append('\n');
}
indent(newindent, writer);
writeString(String.valueOf(key), writer).append(':');
if (indentFactor > 0) {
writer.append(' ');
}
writeValue(map.get(key), writer, indentFactor, newindent);
commanate = true;
}
if (indentFactor > 0) {
writer.append('\n');
}
indent(indent, writer);
}
writer.append('}');
return writer;
} catch (IOException exception) {
throw new JSONException(exception);
}
}
/**
* Determine whether this Iterable has exactly one element. If the
* Iterable is a Collection, just check the {@code size()} method.
* Otherwise, start iterating until we determine whether there is
* more than one element.
*
* @param iterable the Iterable
* @return {@code true} if there is exactly one element, otherwise
* {@code false}
*/
private static boolean singleIterableElement(Iterable<?> iterable) {
if(iterable instanceof Collection) {
return ((Collection)iterable).size() == 1;
}
Iterator<?> iterator = iterable.iterator();
if(!iterator.hasNext()) {
return false;
}
iterator.next();
return !iterator.hasNext();
}
/**
* Write the contents of the Iterable as JSON array to a writer.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @param collection
* The Iterable to be written
* @param writer
* Writes the serialized JSON
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @param indent
* The indention of the top level.
* @param <T> a subtype of {@code Appendable}, returned to the caller
* for chaining purposes
* @return The writer.
* @throws JSONException there was a problem writing the Iterable
*/
static <T extends Appendable> T writeIterable(Iterable<?> collection, T writer,
int indentFactor, int indent) throws JSONException {
try {
boolean singleElement = singleIterableElement(collection);
Iterator<?> iterator = collection.iterator();
boolean commanate = false;
writer.append('[');
if ((singleElement) && (iterator.hasNext())) {
writeValue(iterator.next(), writer,
indentFactor, indent);
} else if (iterator.hasNext()) {
final int newindent = indent + indentFactor;
while (iterator.hasNext()) {
if (commanate) {
writer.append(',');
}
if (indentFactor > 0) {
writer.append('\n');
}
indent(newindent, writer);
writeValue(iterator.next(), writer,
indentFactor, newindent);
commanate = true;
}
if (indentFactor > 0) {
writer.append('\n');
}
indent(indent, writer);
}
writer.append(']');
return writer;
} catch (IOException e) {
throw new JSONException(e);
}
}
/**
* Write the contents of the array as JSON array to a writer.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @param array
* The array to be written
* @param writer
* Writes the serialized JSON
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @param indent
* The indention of the top level.
* @param <T> a subtype of {@code Appendable}, returned to the caller
* for chaining purposes
* @return The writer.
* @throws JSONException there was a problem writing the array
*/
static <T extends Appendable> T writeArray(Object array, T writer,
int indentFactor, int indent) throws JSONException {
try {
final int length = Array.getLength(array);
boolean commanate = false;
writer.append('[');
if (length == 1) {
writeValue(Array.get(array, 0), writer,
indentFactor, indent);
} else if (length != 0) {
final int newindent = indent + indentFactor;
for (int i = 0; i < length; i += 1) {
if (commanate) {
writer.append(',');
}
if (indentFactor > 0) {
writer.append('\n');
}
indent(newindent, writer);
writeValue(Array.get(array, i), writer,
indentFactor, newindent);
commanate = true;
}
if (indentFactor > 0) {
writer.append('\n');
}
indent(indent, writer);
}
writer.append(']');
return writer;
} catch (IOException e) {
throw new JSONException(e);
}
}
/**
* Write the given Enum to the given Appendable as a String.
*
* @param <T> subtype of Appendable, returned to the caller
* @param value
* An Enum
* @param writer
* The Appendable to which the Enum value is written
* @return the given Appendable
* @throws JSONException there was a problem writing the Enum
*/
static <T extends Appendable> T writeEnum(Enum<?> value, T writer)
throws JSONException {
return writeString(value.name(), writer);
}
/**
* Write the contents of the JSONObject as JSON object to a writer.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @param object
* The JSONObject to be written
* @param writer
* Writes the serialized JSON
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @param indent
* The indention of the top level.
* @param <T>
* A subtype of {@code Appendable}, returned to the caller
* for chaining purposes
* @return The writer.
* @throws JSONException there was a problem writing the JSONObject
*/
static <T extends Appendable> T writeJSONObject(JSONObject object, T writer,
int indentFactor, int indent) throws JSONException {
try {
boolean commanate = false;
final int length = object.length();
Iterator<String> keys = object.keys();
writer.append('{');
if (length == 1) {
String key = keys.next();
writeString(key, writer).append(':');
if (indentFactor > 0) {
writer.append(' ');
}
writeValue(object.opt(key), writer, indentFactor, indent);
} else if (length != 0) {
final int newindent = indent + indentFactor;
while (keys.hasNext()) {
String key = keys.next();
if (commanate) {
writer.append(',');
}
if (indentFactor > 0) {
writer.append('\n');
}
indent(newindent, writer);
writeString(key, writer).append(':');
if (indentFactor > 0) {
writer.append(' ');
}
writeValue(object.opt(key), writer, indentFactor, newindent);
commanate = true;
}
if (indentFactor > 0) {
writer.append('\n');
}
indent(indent, writer);
}
writer.append('}');
return writer;
} catch (IOException exception) {
throw new JSONException(exception);
}
}
/**
* Write the contents of the JSONArray as JSON array to a writer.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @param array
* The JSONArray to be written
* @param writer
* Writes the serialized JSON
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @param indent
* The indention of the top level.
* @param <T> a subtype of {@code Appendable}, returned to the caller
* for chaining purposes
* @return The writer.
* @throws JSONException there was a problem writing the JSONArray
*/
static <T extends Appendable> T writeJSONArray(JSONArray array, T writer,
int indentFactor, int indent) throws JSONException {
try {
boolean commanate = false;
int length = array.length();
writer.append('[');
if (length == 1) {
writeValue(array.get(0), writer, indentFactor, indent);
} else if (length != 0) {
final int newindent = indent + indentFactor;
for (int i = 0; i < length; i += 1) {
if (commanate) {
writer.append(',');
}
if (indentFactor > 0) {