/
JSONObjectTest.java
3238 lines (2999 loc) · 147 KB
/
JSONObjectTest.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
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.junit;
/*
Copyright (c) 2020 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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONPointerException;
import org.json.JSONTokener;
import org.json.XML;
import org.json.junit.data.BrokenToString;
import org.json.junit.data.ExceptionalBean;
import org.json.junit.data.Fraction;
import org.json.junit.data.GenericBean;
import org.json.junit.data.GenericBeanInt;
import org.json.junit.data.MyBean;
import org.json.junit.data.MyBeanCustomName;
import org.json.junit.data.MyBeanCustomNameSubClass;
import org.json.junit.data.MyBigNumberBean;
import org.json.junit.data.MyEnum;
import org.json.junit.data.MyEnumField;
import org.json.junit.data.MyJsonString;
import org.json.junit.data.MyNumber;
import org.json.junit.data.MyNumberContainer;
import org.json.junit.data.MyPublicClass;
import org.json.junit.data.Singleton;
import org.json.junit.data.SingletonEnum;
import org.json.junit.data.WeirdList;
import org.junit.Test;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
/**
* JSONObject, along with JSONArray, are the central classes of the reference app.
* All of the other classes interact with them, and JSON functionality would
* otherwise be impossible.
*/
public class JSONObjectTest {
/**
* Regular Expression Pattern that matches JSON Numbers. This is primarily used for
* output to guarantee that we are always writing valid JSON.
*/
static final Pattern NUMBER_PATTERN = Pattern.compile("-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?");
/**
* Tests that the similar method is working as expected.
*/
@Test
public void verifySimilar() {
final String string1 = "HasSameRef";
final String string2 = "HasDifferentRef";
JSONObject obj1 = new JSONObject()
.put("key1", "abc")
.put("key2", 2)
.put("key3", string1);
JSONObject obj2 = new JSONObject()
.put("key1", "abc")
.put("key2", 3)
.put("key3", string1);
JSONObject obj3 = new JSONObject()
.put("key1", "abc")
.put("key2", 2)
.put("key3", new String(string1));
JSONObject obj4 = new JSONObject()
.put("key1", "abc")
.put("key2", 2.0)
.put("key3", new String(string1));
JSONObject obj5 = new JSONObject()
.put("key1", "abc")
.put("key2", 2.0)
.put("key3", new String(string2));
assertFalse("obj1-obj2 Should eval to false", obj1.similar(obj2));
assertTrue("obj1-obj3 Should eval to true", obj1.similar(obj3));
assertTrue("obj1-obj4 Should eval to true", obj1.similar(obj4));
assertFalse("obj1-obj5 Should eval to false", obj1.similar(obj5));
}
@Test
public void timeNumberParsing() {
// test data to use
final String[] testData = new String[] {
null,
"",
"100",
"-100",
"abc123",
"012345",
"100.5e199",
"-100.5e199",
"DEADBEEF",
"0xDEADBEEF",
"1234567890.1234567890",
"-1234567890.1234567890",
"adloghakuidghauiehgauioehgdkjfb nsruoh aeu noerty384 nkljfgh "
+ "395h tdfn kdz8yt3 4hkls gn.ey85 4hzfhnz.o8y5a84 onvklt "
+ "yh389thub nkz8y49lihv al4itlaithknty8hnbl"
// long (in length) number sequences with invalid data at the end of the
// string offer very poor performance for the REGEX.
,"123467890123467890123467890123467890123467890123467890123467"
+ "8901234678901234678901234678901234678901234678901234678"
+ "9012346789012346789012346789012346789012346789012346789"
+ "0a"
};
final int testDataLength = testData.length;
/**
* Changed to 1000 for faster test runs
*/
// final int iterations = 1000000;
final int iterations = 1000;
// 10 million iterations 1,000,000 * 10 (currently 100,000)
long startTime = System.nanoTime();
for(int i = 0; i < iterations; i++) {
for(int j = 0; j < testDataLength; j++) {
try {
BigDecimal v1 = new BigDecimal(testData[j]);
v1.signum();
} catch(Exception ignore) {
//do nothing
}
}
}
final long elapsedNano1 = System.nanoTime() - startTime;
System.out.println("new BigDecimal(testData[]) : " + elapsedNano1 / 1000000 + " ms");
startTime = System.nanoTime();
for(int i = 0; i < iterations; i++) {
for(int j = 0; j < testDataLength; j++) {
try {
boolean v2 = NUMBER_PATTERN.matcher(testData[j]).matches();
assert v2 == !!v2;
} catch(Exception ignore) {
//do nothing
}
}
}
final long elapsedNano2 = System.nanoTime() - startTime;
System.out.println("NUMBER_PATTERN.matcher(testData[]).matches() : " + elapsedNano2 / 1000000 + " ms");
// don't assert normally as the testing is machine dependent.
// assertTrue("Expected Pattern matching to be faster than BigDecimal constructor",elapsedNano2<elapsedNano1);
}
/**
* JSONObject built from a bean, but only using a null value.
* Nothing good is expected to happen.
* Expects NullPointerException
*/
@Test(expected=NullPointerException.class)
public void jsonObjectByNullBean() {
assertNull("Expected an exception",new JSONObject((MyBean)null));
}
/**
* The JSON parser is permissive of unambiguous unquoted keys and values.
* Such JSON text should be allowed, even if it does not strictly conform
* to the spec. However, after being parsed, toString() should emit strictly
* conforming JSON text.
*/
@Test
public void unquotedText() {
String str = "{key1:value1, key2:42}";
JSONObject jsonObject = new JSONObject(str);
String textStr = jsonObject.toString();
assertTrue("expected key1", textStr.contains("\"key1\""));
assertTrue("expected value1", textStr.contains("\"value1\""));
assertTrue("expected key2", textStr.contains("\"key2\""));
assertTrue("expected 42", textStr.contains("42"));
}
@Test
public void testLongFromString(){
String str = "26315000000253009";
JSONObject json = new JSONObject();
json.put("key", str);
final Object actualKey = json.opt("key");
assert str.equals(actualKey) : "Incorrect key value. Got " + actualKey
+ " expected " + str;
final long actualLong = json.optLong("key");
assert actualLong != 0 : "Unable to extract long value for string " + str;
assert 26315000000253009L == actualLong : "Incorrect key value. Got "
+ actualLong + " expected " + str;
final String actualString = json.optString("key");
assert str.equals(actualString) : "Incorrect key value. Got "
+ actualString + " expected " + str;
}
/**
* A JSONObject can be created with no content
*/
@Test
public void emptyJsonObject() {
JSONObject jsonObject = new JSONObject();
assertTrue("jsonObject should be empty", jsonObject.isEmpty());
}
/**
* A JSONObject can be created from another JSONObject plus a list of names.
* In this test, some of the starting JSONObject keys are not in the
* names list.
*/
@Test
public void jsonObjectByNames() {
String str =
"{"+
"\"trueKey\":true,"+
"\"falseKey\":false,"+
"\"nullKey\":null,"+
"\"stringKey\":\"hello world!\","+
"\"escapeStringKey\":\"h\be\tllo w\u1234orld!\","+
"\"intKey\":42,"+
"\"doubleKey\":-23.45e67"+
"}";
String[] keys = {"falseKey", "stringKey", "nullKey", "doubleKey"};
JSONObject jsonObject = new JSONObject(str);
// validate JSON
JSONObject jsonObjectByName = new JSONObject(jsonObject, keys);
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObjectByName.toString());
assertTrue("expected 4 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 4);
assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObjectByName.query("/falseKey")));
assertTrue("expected \"nullKey\":null", JSONObject.NULL.equals(jsonObjectByName.query("/nullKey")));
assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObjectByName.query("/stringKey")));
assertTrue("expected \"doubleKey\":-23.45e67", new BigDecimal("-23.45e67").equals(jsonObjectByName.query("/doubleKey")));
}
/**
* JSONObjects can be built from a Map<String, Object>.
* In this test the map is null.
* the JSONObject(JsonTokener) ctor is not tested directly since it already
* has full coverage from other tests.
*/
@Test
public void jsonObjectByNullMap() {
Map<String, Object> map = null;
JSONObject jsonObject = new JSONObject(map);
assertTrue("jsonObject should be empty", jsonObject.isEmpty());
}
/**
* JSONObjects can be built from a Map<String, Object>.
* In this test all of the map entries are valid JSON types.
*/
@Test
public void jsonObjectByMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("trueKey", new Boolean(true));
map.put("falseKey", new Boolean(false));
map.put("stringKey", "hello world!");
map.put("escapeStringKey", "h\be\tllo w\u1234orld!");
map.put("intKey", new Long(42));
map.put("doubleKey", new Double(-23.45e67));
JSONObject jsonObject = new JSONObject(map);
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 6 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 6);
assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(jsonObject.query("/trueKey")));
assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObject.query("/falseKey")));
assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObject.query("/stringKey")));
assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey")));
assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey")));
}
/**
* Verifies that the constructor has backwards compatability with RAW types pre-java5.
*/
@Test
public void verifyConstructor() {
final JSONObject expected = new JSONObject("{\"myKey\":10}");
@SuppressWarnings("rawtypes")
Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10));
JSONObject jaRaw = new JSONObject(myRawC);
Map<String, Object> myCStrObj = Collections.singletonMap("myKey",
(Object) Integer.valueOf(10));
JSONObject jaStrObj = new JSONObject(myCStrObj);
Map<String, Integer> myCStrInt = Collections.singletonMap("myKey",
Integer.valueOf(10));
JSONObject jaStrInt = new JSONObject(myCStrInt);
Map<?, ?> myCObjObj = Collections.singletonMap((Object) "myKey",
(Object) Integer.valueOf(10));
JSONObject jaObjObj = new JSONObject(myCObjObj);
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaRaw));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaStrObj));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaStrInt));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaObjObj));
}
/**
* Tests Number serialization.
*/
@Test
public void verifyNumberOutput(){
/**
* MyNumberContainer is a POJO, so call JSONObject(bean),
* which builds a map of getter names/values
* The only getter is getMyNumber (key=myNumber),
* whose return value is MyNumber. MyNumber extends Number,
* but is not recognized as such by wrap() per current
* implementation, so wrap() returns the default new JSONObject(bean).
* The only getter is getNumber (key=number), whose return value is
* BigDecimal(42).
*/
JSONObject jsonObject = new JSONObject(new MyNumberContainer());
String actual = jsonObject.toString();
String expected = "{\"myNumber\":{\"number\":42}}";
assertEquals("Equal", expected , actual);
/**
* JSONObject.put() handles objects differently than the
* bean constructor. Where the bean ctor wraps objects before
* placing them in the map, put() inserts the object without wrapping.
* In this case, a MyNumber instance is the value.
* The MyNumber.toString() method is responsible for
* returning a reasonable value: the string '42'.
*/
jsonObject = new JSONObject();
jsonObject.put("myNumber", new MyNumber());
actual = jsonObject.toString();
expected = "{\"myNumber\":42}";
assertEquals("Equal", expected , actual);
/**
* Calls the JSONObject(Map) ctor, which calls wrap() for values.
* AtomicInteger is a Number, but is not recognized by wrap(), per
* current implementation. However, the type is
* 'java.util.concurrent.atomic', so due to the 'java' prefix,
* wrap() inserts the value as a string. That is why 42 comes back
* wrapped in quotes.
*/
jsonObject = new JSONObject(Collections.singletonMap("myNumber", new AtomicInteger(42)));
actual = jsonObject.toString();
expected = "{\"myNumber\":\"42\"}";
assertEquals("Equal", expected , actual);
/**
* JSONObject.put() inserts the AtomicInteger directly into the
* map not calling wrap(). In toString()->write()->writeValue(),
* AtomicInteger is recognized as a Number, and converted via
* numberToString() into the unquoted string '42'.
*/
jsonObject = new JSONObject();
jsonObject.put("myNumber", new AtomicInteger(42));
actual = jsonObject.toString();
expected = "{\"myNumber\":42}";
assertEquals("Equal", expected , actual);
/**
* Calls the JSONObject(Map) ctor, which calls wrap() for values.
* Fraction is a Number, but is not recognized by wrap(), per
* current implementation. As a POJO, Fraction is handled as a
* bean and inserted into a contained JSONObject. It has 2 getters,
* for numerator and denominator.
*/
jsonObject = new JSONObject(Collections.singletonMap("myNumber", new Fraction(4,2)));
assertEquals(1, jsonObject.length());
assertEquals(2, ((JSONObject)(jsonObject.get("myNumber"))).length());
assertEquals("Numerator", BigInteger.valueOf(4) , jsonObject.query("/myNumber/numerator"));
assertEquals("Denominator", BigInteger.valueOf(2) , jsonObject.query("/myNumber/denominator"));
/**
* JSONObject.put() inserts the Fraction directly into the
* map not calling wrap(). In toString()->write()->writeValue(),
* Fraction is recognized as a Number, and converted via
* numberToString() into the unquoted string '4/2'. But the
* BigDecimal sanity check fails, so writeValue() defaults
* to returning a safe JSON quoted string. Pretty slick!
*/
jsonObject = new JSONObject();
jsonObject.put("myNumber", new Fraction(4,2));
actual = jsonObject.toString();
expected = "{\"myNumber\":\"4/2\"}"; // valid JSON, bug fixed
assertEquals("Equal", expected , actual);
}
/**
* Verifies that the put Collection has backwards compatibility with RAW types pre-java5.
*/
@Test
public void verifyPutCollection() {
final JSONObject expected = new JSONObject("{\"myCollection\":[10]}");
@SuppressWarnings("rawtypes")
Collection myRawC = Collections.singleton(Integer.valueOf(10));
JSONObject jaRaw = new JSONObject();
jaRaw.put("myCollection", myRawC);
Collection<Object> myCObj = Collections.singleton((Object) Integer
.valueOf(10));
JSONObject jaObj = new JSONObject();
jaObj.put("myCollection", myCObj);
Collection<Integer> myCInt = Collections.singleton(Integer
.valueOf(10));
JSONObject jaInt = new JSONObject();
jaInt.put("myCollection", myCInt);
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaRaw));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaObj));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaInt));
}
/**
* Verifies that the put Map has backwards compatibility with RAW types pre-java5.
*/
@Test
public void verifyPutMap() {
final JSONObject expected = new JSONObject("{\"myMap\":{\"myKey\":10}}");
@SuppressWarnings("rawtypes")
Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10));
JSONObject jaRaw = new JSONObject();
jaRaw.put("myMap", myRawC);
Map<String, Object> myCStrObj = Collections.singletonMap("myKey",
(Object) Integer.valueOf(10));
JSONObject jaStrObj = new JSONObject();
jaStrObj.put("myMap", myCStrObj);
Map<String, Integer> myCStrInt = Collections.singletonMap("myKey",
Integer.valueOf(10));
JSONObject jaStrInt = new JSONObject();
jaStrInt.put("myMap", myCStrInt);
Map<?, ?> myCObjObj = Collections.singletonMap((Object) "myKey",
(Object) Integer.valueOf(10));
JSONObject jaObjObj = new JSONObject();
jaObjObj.put("myMap", myCObjObj);
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaRaw));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaStrObj));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaStrInt));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaObjObj));
}
/**
* JSONObjects can be built from a Map<String, Object>.
* In this test the map entries are not valid JSON types.
* The actual conversion is kind of interesting.
*/
@Test
public void jsonObjectByMapWithUnsupportedValues() {
Map<String, Object> jsonMap = new HashMap<String, Object>();
// Just insert some random objects
jsonMap.put("key1", new CDL());
jsonMap.put("key2", new Exception());
JSONObject jsonObject = new JSONObject(jsonMap);
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected 0 key1 items", ((Map<?,?>)(JsonPath.read(doc, "$.key1"))).size() == 0);
assertTrue("expected \"key2\":java.lang.Exception","java.lang.Exception".equals(jsonObject.query("/key2")));
}
/**
* JSONObjects can be built from a Map<String, Object>.
* In this test one of the map values is null
*/
@Test
public void jsonObjectByMapWithNullValue() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("trueKey", new Boolean(true));
map.put("falseKey", new Boolean(false));
map.put("stringKey", "hello world!");
map.put("nullKey", null);
map.put("escapeStringKey", "h\be\tllo w\u1234orld!");
map.put("intKey", new Long(42));
map.put("doubleKey", new Double(-23.45e67));
JSONObject jsonObject = new JSONObject(map);
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 6 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 6);
assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(jsonObject.query("/trueKey")));
assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObject.query("/falseKey")));
assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObject.query("/stringKey")));
assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey")));
assertTrue("expected \"intKey\":42", Long.valueOf("42").equals(jsonObject.query("/intKey")));
assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey")));
}
/**
* JSONObject built from a bean. In this case all but one of the
* bean getters return valid JSON types
*/
@SuppressWarnings("boxing")
@Test
public void jsonObjectByBean1() {
/**
* Default access classes have to be mocked since JSONObject, which is
* not in the same package, cannot call MyBean methods by reflection.
*/
MyBean myBean = mock(MyBean.class);
when(myBean.getDoubleKey()).thenReturn(-23.45e7);
when(myBean.getIntKey()).thenReturn(42);
when(myBean.getStringKey()).thenReturn("hello world!");
when(myBean.getEscapeStringKey()).thenReturn("h\be\tllo w\u1234orld!");
when(myBean.isTrueKey()).thenReturn(true);
when(myBean.isFalseKey()).thenReturn(false);
when(myBean.getStringReaderKey()).thenReturn(
new StringReader("") {
});
JSONObject jsonObject = new JSONObject(myBean);
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 8 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 8);
assertTrue("expected 0 items in stringReaderKey", ((Map<?, ?>) (JsonPath.read(doc, "$.stringReaderKey"))).size() == 0);
assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueKey")));
assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseKey")));
assertTrue("expected hello world!","hello world!".equals(jsonObject.query("/stringKey")));
assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey")));
assertTrue("expected 42", Integer.valueOf("42").equals(jsonObject.query("/intKey")));
assertTrue("expected -23.45e7", Double.valueOf("-23.45e7").equals(jsonObject.query("/doubleKey")));
// sorry, mockito artifact
assertTrue("expected 2 callbacks items", ((List<?>)(JsonPath.read(doc, "$.callbacks"))).size() == 2);
assertTrue("expected 0 handler items", ((Map<?,?>)(JsonPath.read(doc, "$.callbacks[0].handler"))).size() == 0);
assertTrue("expected 0 callbacks[1] items", ((Map<?,?>)(JsonPath.read(doc, "$.callbacks[1]"))).size() == 0);
}
/**
* JSONObject built from a bean that has custom field names.
*/
@Test
public void jsonObjectByBean2() {
JSONObject jsonObject = new JSONObject(new MyBeanCustomName());
assertNotNull(jsonObject);
assertEquals("Wrong number of keys found:",
5,
jsonObject.keySet().size());
assertFalse("Normal field name (someString) processing did not work",
jsonObject.has("someString"));
assertFalse("Normal field name (myDouble) processing did not work",
jsonObject.has("myDouble"));
assertFalse("Normal field name (someFloat) processing did not work",
jsonObject.has("someFloat"));
assertFalse("Ignored field not found!",
jsonObject.has("ignoredInt"));
// getSomeInt() has no user-defined annotation
assertTrue("Normal field name (someInt) should have been found",
jsonObject.has("someInt"));
// the user-defined annotation does not replace any value, so someLong should be found
assertTrue("Normal field name (someLong) should have been found",
jsonObject.has("someLong"));
// myStringField replaces someString property name via user-defined annotation
assertTrue("Overridden String field name (myStringField) should have been found",
jsonObject.has("myStringField"));
// weird name replaces myDouble property name via user-defined annotation
assertTrue("Overridden String field name (Some Weird NAme that Normally Wouldn't be possible!) should have been found",
jsonObject.has("Some Weird NAme that Normally Wouldn't be possible!"));
// InterfaceField replaces someFloat property name via user-defined annotation
assertTrue("Overridden String field name (InterfaceField) should have been found",
jsonObject.has("InterfaceField"));
}
/**
* JSONObject built from a bean that has custom field names inherited from a parent class.
*/
@Test
public void jsonObjectByBean3() {
JSONObject jsonObject = new JSONObject(new MyBeanCustomNameSubClass());
assertNotNull(jsonObject);
assertEquals("Wrong number of keys found:",
7,
jsonObject.keySet().size());
assertFalse("Normal int field name (someInt) found, but was overridden",
jsonObject.has("someInt"));
assertFalse("Normal field name (myDouble) processing did not work",
jsonObject.has("myDouble"));
// myDouble was replaced by weird name, and then replaced again by AMoreNormalName via user-defined annotation
assertFalse("Overridden String field name (Some Weird NAme that Normally Wouldn't be possible!) should not be FOUND!",
jsonObject.has("Some Weird NAme that Normally Wouldn't be possible!"));
assertFalse("Normal field name (someFloat) found, but was overridden",
jsonObject.has("someFloat"));
assertFalse("Ignored field found! but was overridden",
jsonObject.has("ignoredInt"));
// shouldNotBeJSON property name was first ignored, then replaced by ShouldBeIgnored via user-defined annotations
assertFalse("Ignored field at the same level as forced name should not have been found",
jsonObject.has("ShouldBeIgnored"));
// able property name was replaced by Getable via user-defined annotation
assertFalse("Normally ignored field (able) with explicit property name should not have been found",
jsonObject.has("able"));
// property name someInt was replaced by newIntFieldName via user-defined annotation
assertTrue("Overridden int field name (newIntFieldName) should have been found",
jsonObject.has("newIntFieldName"));
// property name someLong was not replaced via user-defined annotation
assertTrue("Normal field name (someLong) should have been found",
jsonObject.has("someLong"));
// property name someString was replaced by myStringField via user-defined annotation
assertTrue("Overridden String field name (myStringField) should have been found",
jsonObject.has("myStringField"));
// property name myDouble was replaced by a weird name, followed by AMoreNormalName via user-defined annotations
assertTrue("Overridden double field name (AMoreNormalName) should have been found",
jsonObject.has("AMoreNormalName"));
// property name someFloat was replaced by InterfaceField via user-defined annotation
assertTrue("Overridden String field name (InterfaceField) should have been found",
jsonObject.has("InterfaceField"));
// property name ignoredInt was replaced by none, followed by forcedInt via user-defined annotations
assertTrue("Forced field should have been found!",
jsonObject.has("forcedInt"));
// property name able was replaced by Getable via user-defined annotation
assertTrue("Overridden boolean field name (Getable) should have been found",
jsonObject.has("Getable"));
}
/**
* A bean is also an object. But in order to test the JSONObject
* ctor that takes an object and a list of names,
* this particular bean needs some public
* data members, which have been added to the class.
*/
@Test
public void jsonObjectByObjectAndNames() {
String[] keys = {"publicString", "publicInt"};
// just need a class that has public data members
MyPublicClass myPublicClass = new MyPublicClass();
JSONObject jsonObject = new JSONObject(myPublicClass, keys);
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected \"publicString\":\"abc\"", "abc".equals(jsonObject.query("/publicString")));
assertTrue("expected \"publicInt\":42", Integer.valueOf(42).equals(jsonObject.query("/publicInt")));
}
/**
* Exercise the JSONObject from resource bundle functionality.
* The test resource bundle is uncomplicated, but provides adequate test coverage.
*/
@Test
public void jsonObjectByResourceBundle() {
JSONObject jsonObject = new
JSONObject("org.json.junit.data.StringsResourceBundle",
Locale.getDefault());
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected 2 greetings items", ((Map<?,?>)(JsonPath.read(doc, "$.greetings"))).size() == 2);
assertTrue("expected \"hello\":\"Hello, \"", "Hello, ".equals(jsonObject.query("/greetings/hello")));
assertTrue("expected \"world\":\"World!\"", "World!".equals(jsonObject.query("/greetings/world")));
assertTrue("expected 2 farewells items", ((Map<?,?>)(JsonPath.read(doc, "$.farewells"))).size() == 2);
assertTrue("expected \"later\":\"Later, \"", "Later, ".equals(jsonObject.query("/farewells/later")));
assertTrue("expected \"world\":\"World!\"", "Alligator!".equals(jsonObject.query("/farewells/gator")));
}
/**
* Exercise the JSONObject.accumulate() method
*/
@SuppressWarnings("boxing")
@Test
public void jsonObjectAccumulate() {
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("myArray", true);
jsonObject.accumulate("myArray", false);
jsonObject.accumulate("myArray", "hello world!");
jsonObject.accumulate("myArray", "h\be\tllo w\u1234orld!");
jsonObject.accumulate("myArray", 42);
jsonObject.accumulate("myArray", -23.45e7);
// include an unsupported object for coverage
try {
jsonObject.accumulate("myArray", Double.NaN);
fail("Expected exception");
} catch (JSONException ignored) {}
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1);
assertTrue("expected 6 myArray items", ((List<?>)(JsonPath.read(doc, "$.myArray"))).size() == 6);
assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/myArray/0")));
assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/myArray/1")));
assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/myArray/2")));
assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/myArray/3")));
assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/myArray/4")));
assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5")));
}
/**
* Exercise the JSONObject append() functionality
*/
@SuppressWarnings("boxing")
@Test
public void jsonObjectAppend() {
JSONObject jsonObject = new JSONObject();
jsonObject.append("myArray", true);
jsonObject.append("myArray", false);
jsonObject.append("myArray", "hello world!");
jsonObject.append("myArray", "h\be\tllo w\u1234orld!");
jsonObject.append("myArray", 42);
jsonObject.append("myArray", -23.45e7);
// include an unsupported object for coverage
try {
jsonObject.append("myArray", Double.NaN);
fail("Expected exception");
} catch (JSONException ignored) {}
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1);
assertTrue("expected 6 myArray items", ((List<?>)(JsonPath.read(doc, "$.myArray"))).size() == 6);
assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/myArray/0")));
assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/myArray/1")));
assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/myArray/2")));
assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/myArray/3")));
assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/myArray/4")));
assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5")));
}
/**
* Exercise the JSONObject doubleToString() method
*/
@SuppressWarnings("boxing")
@Test
public void jsonObjectDoubleToString() {
String [] expectedStrs = {"1", "1", "-23.4", "-2.345E68", "null", "null" };
Double [] doubles = { 1.0, 00001.00000, -23.4, -23.45e67,
Double.NaN, Double.NEGATIVE_INFINITY };
for (int i = 0; i < expectedStrs.length; ++i) {
String actualStr = JSONObject.doubleToString(doubles[i]);
assertTrue("value expected ["+expectedStrs[i]+
"] found ["+actualStr+ "]",
expectedStrs[i].equals(actualStr));
}
}
/**
* Exercise some JSONObject get[type] and opt[type] methods
*/
@Test
public void jsonObjectValues() {
String str =
"{"+
"\"trueKey\":true,"+
"\"falseKey\":false,"+
"\"trueStrKey\":\"true\","+
"\"falseStrKey\":\"false\","+
"\"stringKey\":\"hello world!\","+
"\"intKey\":42,"+
"\"intStrKey\":\"43\","+
"\"longKey\":1234567890123456789,"+
"\"longStrKey\":\"987654321098765432\","+
"\"doubleKey\":-23.45e7,"+
"\"doubleStrKey\":\"00001.000\","+
"\"BigDecimalStrKey\":\"19007199254740993.35481234487103587486413587843213584\","+
"\"negZeroKey\":-0.0,"+
"\"negZeroStrKey\":\"-0.0\","+
"\"arrayKey\":[0,1,2],"+
"\"objectKey\":{\"myKey\":\"myVal\"}"+
"}";
JSONObject jsonObject = new JSONObject(str);
assertTrue("trueKey should be true", jsonObject.getBoolean("trueKey"));
assertTrue("opt trueKey should be true", jsonObject.optBoolean("trueKey"));
assertTrue("falseKey should be false", !jsonObject.getBoolean("falseKey"));
assertTrue("trueStrKey should be true", jsonObject.getBoolean("trueStrKey"));
assertTrue("trueStrKey should be true", jsonObject.optBoolean("trueStrKey"));
assertTrue("falseStrKey should be false", !jsonObject.getBoolean("falseStrKey"));
assertTrue("stringKey should be string",
jsonObject.getString("stringKey").equals("hello world!"));
assertTrue("doubleKey should be double",
jsonObject.getDouble("doubleKey") == -23.45e7);
assertTrue("doubleStrKey should be double",
jsonObject.getDouble("doubleStrKey") == 1);
assertTrue("doubleKey can be float",
jsonObject.getFloat("doubleKey") == -23.45e7f);
assertTrue("doubleStrKey can be float",
jsonObject.getFloat("doubleStrKey") == 1f);
assertTrue("opt doubleKey should be double",
jsonObject.optDouble("doubleKey") == -23.45e7);
assertTrue("opt doubleKey with Default should be double",
jsonObject.optDouble("doubleStrKey", Double.NaN) == 1);
assertTrue("opt negZeroKey should be a Double",
jsonObject.opt("negZeroKey") instanceof Double);
assertTrue("get negZeroKey should be a Double",
jsonObject.get("negZeroKey") instanceof Double);
assertTrue("optNumber negZeroKey should return Double",
jsonObject.optNumber("negZeroKey") instanceof Double);
assertTrue("optNumber negZeroStrKey should return Double",
jsonObject.optNumber("negZeroStrKey") instanceof Double);
assertTrue("opt negZeroKey should be double",
Double.compare(jsonObject.optDouble("negZeroKey"), -0.0d) == 0);
assertTrue("opt negZeroStrKey with Default should be double",
Double.compare(jsonObject.optDouble("negZeroStrKey"), -0.0d) == 0);
assertTrue("optNumber negZeroKey should be -0.0",
Double.compare(jsonObject.optNumber("negZeroKey").doubleValue(), -0.0d) == 0);
assertTrue("optNumber negZeroStrKey should be -0.0",
Double.compare(jsonObject.optNumber("negZeroStrKey").doubleValue(), -0.0d) == 0);
assertTrue("optFloat doubleKey should be float",
jsonObject.optFloat("doubleKey") == -23.45e7f);
assertTrue("optFloat doubleKey with Default should be float",
jsonObject.optFloat("doubleStrKey", Float.NaN) == 1f);
assertTrue("intKey should be int",
jsonObject.optInt("intKey") == 42);
assertTrue("opt intKey should be int",
jsonObject.optInt("intKey", 0) == 42);
assertTrue("opt intKey with default should be int",
jsonObject.getInt("intKey") == 42);
assertTrue("intStrKey should be int",
jsonObject.getInt("intStrKey") == 43);
assertTrue("longKey should be long",
jsonObject.getLong("longKey") == 1234567890123456789L);
assertTrue("opt longKey should be long",
jsonObject.optLong("longKey") == 1234567890123456789L);
assertTrue("opt longKey with default should be long",
jsonObject.optLong("longKey", 0) == 1234567890123456789L);
assertTrue("longStrKey should be long",
jsonObject.getLong("longStrKey") == 987654321098765432L);
assertTrue("optNumber int should return Integer",
jsonObject.optNumber("intKey") instanceof Integer);
assertTrue("optNumber long should return Long",
jsonObject.optNumber("longKey") instanceof Long);
assertTrue("optNumber double should return BigDecimal",
jsonObject.optNumber("doubleKey") instanceof BigDecimal);
assertTrue("optNumber Str int should return Integer",
jsonObject.optNumber("intStrKey") instanceof Integer);
assertTrue("optNumber Str long should return Long",
jsonObject.optNumber("longStrKey") instanceof Long);
assertTrue("optNumber Str double should return BigDecimal",
jsonObject.optNumber("doubleStrKey") instanceof BigDecimal);
assertTrue("optNumber BigDecimalStrKey should return BigDecimal",
jsonObject.optNumber("BigDecimalStrKey") instanceof BigDecimal);
assertTrue("xKey should not exist",
jsonObject.isNull("xKey"));
assertTrue("stringKey should exist",
jsonObject.has("stringKey"));
assertTrue("opt stringKey should string",
jsonObject.optString("stringKey").equals("hello world!"));
assertTrue("opt stringKey with default should string",
jsonObject.optString("stringKey", "not found").equals("hello world!"));
JSONArray jsonArray = jsonObject.getJSONArray("arrayKey");
assertTrue("arrayKey should be JSONArray",
jsonArray.getInt(0) == 0 &&
jsonArray.getInt(1) == 1 &&
jsonArray.getInt(2) == 2);
jsonArray = jsonObject.optJSONArray("arrayKey");
assertTrue("opt arrayKey should be JSONArray",
jsonArray.getInt(0) == 0 &&
jsonArray.getInt(1) == 1 &&
jsonArray.getInt(2) == 2);
JSONObject jsonObjectInner = jsonObject.getJSONObject("objectKey");
assertTrue("objectKey should be JSONObject",
jsonObjectInner.get("myKey").equals("myVal"));
}
/**
* Check whether JSONObject handles large or high precision numbers correctly
*/
@Test
public void stringToValueNumbersTest() {
assertTrue("-0 Should be a Double!",JSONObject.stringToValue("-0") instanceof Double);
assertTrue("-0.0 Should be a Double!",JSONObject.stringToValue("-0.0") instanceof Double);
assertTrue("'-' Should be a String!",JSONObject.stringToValue("-") instanceof String);
assertTrue( "0.2 should be a Double!",
JSONObject.stringToValue( "0.2" ) instanceof BigDecimal );
assertTrue( "Doubles should be BigDecimal, even when incorrectly converting floats!",
JSONObject.stringToValue( new Double( "0.2f" ).toString() ) instanceof BigDecimal );
/**
* This test documents a need for BigDecimal conversion.
*/
Object obj = JSONObject.stringToValue( "299792.457999999984" );
assertTrue( "does not evaluate to 299792.457999999984 BigDecimal!",
obj.equals(new BigDecimal("299792.457999999984")) );
assertTrue( "1 should be an Integer!",
JSONObject.stringToValue( "1" ) instanceof Integer );
assertTrue( "Integer.MAX_VALUE should still be an Integer!",
JSONObject.stringToValue( new Integer( Integer.MAX_VALUE ).toString() ) instanceof Integer );
assertTrue( "Large integers should be a Long!",
JSONObject.stringToValue( Long.valueOf(((long)Integer.MAX_VALUE) + 1 ) .toString() ) instanceof Long );
assertTrue( "Long.MAX_VALUE should still be an Integer!",
JSONObject.stringToValue( new Long( Long.MAX_VALUE ).toString() ) instanceof Long );
String str = new BigInteger( new Long( Long.MAX_VALUE ).toString() ).add( BigInteger.ONE ).toString();
assertTrue( "Really large integers currently evaluate to BigInteger",
JSONObject.stringToValue(str).equals(new BigInteger("9223372036854775808")));
}
/**
* This test documents numeric values which could be numerically
* handled as BigDecimal or BigInteger. It helps determine what outputs
* will change if those types are supported.
*/
@Test
public void jsonValidNumberValuesNeitherLongNorIEEE754Compatible() {
// Valid JSON Numbers, probably should return BigDecimal or BigInteger objects
String str =
"{"+
"\"numberWithDecimals\":299792.457999999984,"+
"\"largeNumber\":12345678901234567890,"+
"\"preciseNumber\":0.2000000000000000111,"+
"\"largeExponent\":-23.45e2327"+
"}";
JSONObject jsonObject = new JSONObject(str);
// Comes back as a double, but loses precision
assertTrue( "numberWithDecimals currently evaluates to double 299792.458",
jsonObject.get( "numberWithDecimals" ).equals( new BigDecimal( "299792.457999999984" ) ) );
Object obj = jsonObject.get( "largeNumber" );
assertTrue("largeNumber currently evaluates to BigInteger",
new BigInteger("12345678901234567890").equals(obj));
// comes back as a double but loses precision
assertEquals( "preciseNumber currently evaluates to double 0.2",
0.2, jsonObject.getDouble( "preciseNumber" ), 0.0);
obj = jsonObject.get( "largeExponent" );
assertTrue("largeExponent should evaluate as a BigDecimal",
new BigDecimal("-23.45e2327").equals(obj));
}