-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
JsonPath.java
1095 lines (1015 loc) · 36.1 KB
/
JsonPath.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
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.restassured.path.json;
import groovy.json.JsonBuilder;
import groovy.json.JsonOutput;
import io.restassured.common.mapper.TypeRef;
import io.restassured.internal.common.assertion.AssertParameter;
import io.restassured.internal.common.path.ObjectConverter;
import io.restassured.internal.path.json.ConfigurableJsonSlurper;
import io.restassured.internal.path.json.JSONAssertion;
import io.restassured.internal.path.json.JsonPrettifier;
import io.restassured.internal.path.json.mapping.JsonObjectDeserializer;
import io.restassured.path.json.config.JsonParserType;
import io.restassured.path.json.config.JsonPathConfig;
import io.restassured.path.json.exception.JsonPathException;
import io.restassured.path.json.mapper.factory.GsonObjectMapperFactory;
import io.restassured.path.json.mapper.factory.Jackson1ObjectMapperFactory;
import io.restassured.path.json.mapper.factory.Jackson2ObjectMapperFactory;
import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.Map.Entry;
/**
* JsonPath is an alternative to using XPath for easily getting values from a Object document. It follows the
* Groovy <a href="http://docs.groovy-lang.org/latest/html/documentation/#_gpath">GPath</a> syntax when getting an object from the document. You can regard it as an alternative to XPath for JSON.
* E.g. given the following Object document:
* <pre>
* { "store": {
* "book": [
* { "category": "reference",
* "author": "Nigel Rees",
* "title": "Sayings of the Century",
* "price": 8.95
* },
* { "category": "fiction",
* "author": "Evelyn Waugh",
* "title": "Sword of Honour",
* "price": 12.99
* },
* { "category": "fiction",
* "author": "Herman Melville",
* "title": "Moby Dick",
* "isbn": "0-553-21311-3",
* "price": 8.99
* },
* { "category": "fiction",
* "author": "J. R. R. Tolkien",
* "title": "The Lord of the Rings",
* "isbn": "0-395-19395-8",
* "price": 22.99
* }
* ],
* "bicycle": {
* "color": "red",
* "price": 19.95
* }
* }
* }
* </pre>
* To get a list of all book categories:
* <pre>
* List<String> categories = with(Object).get("store.book.category");
* </pre>
* <p/>
* Get the first book category:
* <pre>
* String category = with(Object).get("store.book[0].category");
* </pre>
* <p/>
* Get the last book category:
* <pre>
* String category = with(Object).get("store.book[-1].category");
* </pre>
* <p/>
* Get all books with price between 5 and 15:
* <pre>
* List<Map> books = with(Object).get("store.book.findAll { book -> book.price >= 5 && book.price <= 15 }");
* </pre>
* <p/>
* The JsonPath implementation of rest-assured uses a Groovy shell to evaluate expressions so be careful when injecting
* user input into the expression. For example avoid doing this:
* <pre>
* String name = System.console().readLine();
* List<Map> books = with(Object).get("store.book.findAll { book -> book.author == " + name + " }");
* </pre>
* Instead use the {@link #param(java.lang.String, java.lang.Object)} method like this:
* <pre>
* String name = System.console().readLine();
* List<Map> books = with(Object).param("name", name).get("store.book.findAll { book -> book.author == name }");
* </pre>
*/
public class JsonPath {
public static JsonPathConfig config = null;
private final JsonParser jsonParser;
private JsonPathConfig jsonPathConfig = null;
private String rootPath = "";
/**
* Parameters for groovy console (not initialized here to save memory for queries that don't use params)
*/
private Map<String, Object> params;
/**
* Instantiate a new JsonPath instance.
*
* @param text The text containing the Object document
*/
public JsonPath(String text) {
jsonParser = parseText(text);
}
/**
* Instantiate a new JsonPath instance.
*
* @param url The url containing the Object document
*/
public JsonPath(URL url) {
jsonParser = parseURL(url);
}
/**
* Instantiate a new JsonPath instance.
*
* @param stream The stream containing the Object document
*/
public JsonPath(InputStream stream) {
jsonParser = parseInputStream(stream);
}
/**
* Instantiate a new JsonPath instance.
*
* @param file The file containing the Object document
*/
public JsonPath(File file) {
jsonParser = parseFile(file);
}
/**
* Instantiate a new JsonPath instance.
*
* @param reader The reader containing the Object document
*/
public JsonPath(Reader reader) {
jsonParser = parseReader(reader);
}
private JsonPath(JsonPath jsonPath, JsonPathConfig jsonPathConfig) {
this.jsonPathConfig = jsonPathConfig;
this.jsonParser = jsonPath.jsonParser;
this.rootPath = jsonPath.rootPath;
if (jsonPath.params != null) {
this.params = new HashMap<>(jsonPath.params);
}
}
/**
* Get a Object graph with no named root element as a Java object. This is just a short-cut for
* <p/>
* <pre>
* get("");
* </pre>
* or
* <pre>
* get("$");
* </pre>
*
* @return The object matching the Object graph. This may be any primitive type, a List or a Map. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public <T> T get() {
return get("");
}
/**
* Get the result of an Object path expression as a boolean.
*
* @param path The Object path.
* @return The object matching the Object path. This may be any primitive type, a List or a Map. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public <T> T get(String path) {
final JSONAssertion jsonAssertion = createJsonAssertion(path, params);
final Object json = jsonParser.parseWith(createConfigurableJsonSlurper());
return (T) jsonAssertion.getResult(json, null);
}
/**
* Get the result of an Object path expression as a boolean
*
* @param path The Object path.
* @return The object matching the Object path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public boolean getBoolean(String path) {
return ObjectConverter.convertObjectTo(get(path), Boolean.class);
}
/**
* Get the result of an Object path expression as a char.
*
* @param path The Object path.
* @return The object matching the Object path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public char getChar(String path) {
return ObjectConverter.convertObjectTo(get(path), Character.class);
}
/**
* Get the result of an Object path expression as an int.
*
* @param path The Object path.
* @return The int matching the Object path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public int getInt(String path) {
//The type returned from Groovy depends on the input, so we need to handle different numerical types.
Object value = get(path);
if (value instanceof Integer) {
return (Integer) value;
} else if (value instanceof Short) {
return ((Short) value).intValue();
} else if (value instanceof Long) {
return ((Long) value).intValue();
} else {
return ObjectConverter.convertObjectTo(value, Integer.class);
}
}
/**
* Get the result of an Object path expression as a byte.
*
* @param path The Object path.
* @return The object matching the Object path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public byte getByte(String path) {
//The type returned from Groovy depends on the input, so we need to handle different numerical types.
Object value = get(path);
if (value instanceof Byte) {
return (Byte) value;
} else if (value instanceof Long) {
return ((Long) value).byteValue();
} else if (value instanceof Integer) {
return ((Integer) value).byteValue();
} else {
return ObjectConverter.convertObjectTo(value, Byte.class);
}
}
/**
* Get the result of an Object path expression as a short.
*
* @param path The Object path.
* @return The object matching the Object path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public short getShort(String path) {
//The type returned from Groovy depends on the input, so we need to handle different numerical types.
Object value = get(path);
if (value instanceof Short) {
return (Short) value;
} else if (value instanceof Long) {
return ((Long) value).shortValue();
} else if (value instanceof Integer) {
return ((Integer) value).shortValue();
} else {
return ObjectConverter.convertObjectTo(value, Short.class);
}
}
/**
* Get the result of an Object path expression as a float.
*
* @param path The Object path.
* @return The object matching the Object path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public float getFloat(String path) {
final Object value = get(path);
//Groovy will always return a Double for floating point values.
if (value instanceof Double) {
return ((Double) value).floatValue();
} else {
return ObjectConverter.convertObjectTo(value, Float.class);
}
}
/**
* Get the result of an Object path expression as a double.
*
* @param path The Object path.
* @return The object matching the Object path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public double getDouble(String path) {
final Object value = get(path);
if (value instanceof Double) {
return (Double) value;
}
return ObjectConverter.convertObjectTo(value, Double.class);
}
/**
* Get the result of an Object path expression as a long.
*
* @param path The Object path.
* @return The object matching the Object path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public long getLong(String path) {
//The type returned from Groovy depends on the input, so we need to handle different numerical types.
Object value = get(path);
if (value instanceof Long) {
return (Long) value;
} else if (value instanceof Short) {
return ((Short) value).longValue();
} else if (value instanceof Integer) {
return ((Integer) value).longValue();
} else {
return ObjectConverter.convertObjectTo(value, Long.class);
}
}
/**
* Get the result of an Object path expression as a string.
*
* @param path The Object path.
* @return The object matching the Object path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public String getString(String path) {
return ObjectConverter.convertObjectTo(get(path), String.class);
}
/**
* Get the result of an Object path expression as a UUID.
*
* @param path The Object path.
* @return The object matching the Object path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public UUID getUUID(String path) {
return ObjectConverter.convertObjectTo(get(path), UUID.class);
}
/**
* Get the result of an Object path expression as a list.
*
* @param path The Object path.
* @param <T> The list type
* @return The object matching the Object path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public <T> List<T> getList(String path) {
return get(path);
}
/**
* Get the result of an Object path expression as a list.
*
* @param path The Object path.
* @param genericType The generic list type
* @param <T> The type
* @return The object matching the Object path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public <T> List<T> getList(String path, Class<T> genericType) {
if (genericType == null) {
throw new IllegalArgumentException("Generic type cannot be null");
}
final List<T> original = get(path);
final List<T> newList = new LinkedList<>();
if (original != null) {
for (T t : original) {
T e;
if (t instanceof Map && !genericType.isAssignableFrom(Map.class)) {
// TODO Avoid double parsing
String str = objectToString(t);
//noinspection unchecked
e = (T) jsonStringToObject(str, genericType);
} else {
e = ObjectConverter.convertObjectTo(t, genericType);
}
newList.add(e);
}
}
return Collections.unmodifiableList(newList);
}
/**
* Get the result of an Object path expression as a map.
*
* @param path The Object path.
* @param <K> The type of the expected key
* @param <V> The type of the expected value
* @return The map matching the Object path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public <K, V> Map<K, V> getMap(String path) {
return get(path);
}
/**
* Get the result of an Object path expression as a map.
*
* @param path The Object path.
* @param keyType The type of the expected key
* @param valueType The type of the expected value
* @param <K> The type of the expected key
* @param <V> The type of the expected value
* @return The map matching the Object path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public <K, V> Map<K, V> getMap(String path, Class<K> keyType, Class<V> valueType) {
final Map<K, V> originalMap = get(path);
final Map<K, V> newMap = new HashMap<>();
for (Entry<K, V> entry : originalMap.entrySet()) {
final K key = entry.getKey() == null ? null : ObjectConverter.convertObjectTo(entry.getKey(), keyType);
final V value = entry.getValue() == null ? null : ObjectConverter.convertObjectTo(entry.getValue(), valueType);
newMap.put(key, value);
}
return Collections.unmodifiableMap(newMap);
}
/**
* Get the result of a Object path expression as a java Object.
* E.g. given the following Object document:
* <pre>
* { "store": {
* "book": [
* { "category": "reference",
* "author": "Nigel Rees",
* "title": "Sayings of the Century",
* "price": 8.95
* },
* { "category": "fiction",
* "author": "Evelyn Waugh",
* "title": "Sword of Honour",
* "price": 12.99
* },
* { "category": "fiction",
* "author": "Herman Melville",
* "title": "Moby Dick",
* "isbn": "0-553-21311-3",
* "price": 8.99
* },
* { "category": "fiction",
* "author": "J. R. R. Tolkien",
* "title": "The Lord of the Rings",
* "isbn": "0-395-19395-8",
* "price": 22.99
* }
* ],
* "bicycle": {
* "color": "red",
* "price": 19.95
* }
* }
* }
* </pre>
* And a Java object like this:
* <p/>
* <pre>
* public class Book {
* private String category;
* private String author;
* private String title;
* private String isbn;
* private float price;
*
* public String getCategory() {
* return category;
* }
*
* public void setCategory(String category) {
* this.category = category;
* }
*
* public String getAuthor() {
* return author;
* }
*
* public void setAuthor(String author) {
* this.author = author;
* }
*
* public String getTitle() {
* return title;
* }
*
* public void setTitle(String title) {
* this.title = title;
* }
*
* public String getIsbn() {
* return isbn;
* }
*
* public void setIsbn(String isbn) {
* this.isbn = isbn;
* }
*
* public float getPrice() {
* return price;
* }
*
* public void setPrice(float price) {
* this.price = price;
* }
* }
* </pre>
* <p/>
* Then
* <pre>
* Book book = from(Object).getObject("store.book[2]", Book.class);
* </pre>
* <p/>
* maps the second book to a Book instance.
*
* @param path The path to the object to map
* @param objectType The class type of the expected object
* @param <T> The type of the expected object
* @return The object
*/
public <T> T getObject(String path, Class<T> objectType) {
Object object = getJsonObject(path);
if (object == null) {
return null;
} else if (object instanceof List || object instanceof Map) {
// TODO Avoid double parsing
object = objectToString(object);
} else {
return ObjectConverter.convertObjectTo(object, objectType);
}
if (!(object instanceof String)) {
throw new IllegalStateException("Internal error: Json object was not an instance of String, please report to the REST Assured mailing-list.");
}
return (T) jsonStringToObject((String) object, objectType);
}
/**
* Get the result of a Object path expression as a java Object with generic type.
* E.g. given the following Object document:
* <pre>
* { "store": {
* "book": [
* { "category": "reference",
* "author": "Nigel Rees",
* "title": "Sayings of the Century",
* "price": 8.95
* },
* { "category": "fiction",
* "author": "Evelyn Waugh",
* "title": "Sword of Honour",
* "price": 12.99
* },
* { "category": "fiction",
* "author": "Herman Melville",
* "title": "Moby Dick",
* "isbn": "0-553-21311-3",
* "price": 8.99
* },
* { "category": "fiction",
* "author": "J. R. R. Tolkien",
* "title": "The Lord of the Rings",
* "isbn": "0-395-19395-8",
* "price": 22.99
* }
* ],
* "bicycle": {
* "color": "red",
* "price": 19.95
* }
* }
* }
* </pre>
* And you want to get a book as a <code>Map<String, Object></code>:
* <p/>
* Then
* <pre>
* Map<String, Object> book = from(Object).getObject("store.book[2]", new TypeRef<Map<String, Object>>() {});
* </pre>
* <p/>
* maps the second book to a Book instance.
*
* @param path The path to the object to map
* @param typeRef The class type of the expected object
* @param <T> The type of the expected object
* @return The object
*/
public <T> T getObject(String path, TypeRef<T> typeRef) {
AssertParameter.notNull("objectType", "Type ref");
return getObject(path, typeRef.getTypeAsClass());
}
/**
* Add a parameter for the expression. Example:
* <pre>
* String name = System.console().readLine();
* List<Map> books = with(Object).param("name", name).get("store.book.findAll { book -> book.author == name }");
* </pre>
*
* @param key The name of the parameter. Just use this name in your expression as a variable
* @param value The value of the parameter
* @return New JsonPath instance with the parameter set
*/
public JsonPath param(String key, Object value) {
JsonPath newP = new JsonPath(this, config);
if (newP.params == null) {
newP.params = new HashMap<>();
}
newP.params.put(key, value);
return newP;
}
/**
* Peeks into the JSON that JsonPath will parse by printing it to the console. You can
* continue working with JsonPath afterwards. This is mainly for debug purposes. If you want to return a prettified version of the content
* see {@link #prettify()}. If you want to return a prettified version of the content and also print it to the console use {@link #prettyPrint()}.
* <p/>
* <p>
* Note that the content is not guaranteed to be looking exactly like the it does at the source. This is because once you peek
* the content has been downloaded and transformed into another data structure (used by JsonPath) and the JSON is rendered
* from this data structure.
* </p>
*
* @return The same JsonPath instance
*/
public JsonPath peek() {
System.out.println(toJsonString());
return this;
}
/**
* Peeks into the JSON that JsonPath will parse by printing it to the console in a prettified manner. You can
* continue working with JsonPath afterwards. This is mainly for debug purposes. If you want to return a prettified version of the content
* see {@link #prettify()}. If you want to return a prettified version of the content and also print it to the console use {@link #prettyPrint()}.
* <p/>
* <p>
* Note that the content is not guaranteed to be looking exactly like the it does at the source. This is because once you peek
* the content has been downloaded and transformed into another data structure (used by JsonPath) and the JSON is rendered
* from this data structure.
* </p>
*
* @return The same JsonPath instance
*/
public JsonPath prettyPeek() {
prettyPrint();
return this;
}
/**
* Get the JSON as a prettified string.
* <p>
* Note that the content is not guaranteed to be looking exactly like the it does at the source. This is because once you peek
* the content has been downloaded and transformed into another data structure (used by JsonPath) and the JSON is rendered
* from this data structure.
* </p>
*
* @return The JSON as a prettified String.
*/
public String prettify() {
final String jsonString = toJsonString();
return JsonPrettifier.prettifyJson(jsonString);
}
/**
* Get and print the JSON as a prettified string.
* <p>
* Note that the content is not guaranteed to be looking exactly like the it does at the source. This is because once you peek
* the content has been downloaded and transformed into another data structure (used by JsonPath) and the JSON is rendered
* from this data structure.
* </p>
*
* @return The JSON as a prettified String.
*/
public String prettyPrint() {
final String pretty = prettify();
System.out.println(pretty);
return pretty;
}
/**
* Configure JsonPath to use a specific Gson object mapper factory
*
* @param factory The gson object mapper factory instance
* @return a new JsonPath instance
*/
public JsonPath using(GsonObjectMapperFactory factory) {
return new JsonPath(this, jsonPathConfig.gsonObjectMapperFactory(factory));
}
/**
* Configure JsonPath to use a specific Jackson object mapper factory
*
* @param factory The Jackson object mapper factory instance
* @return a new JsonPath instance
*/
public JsonPath using(Jackson1ObjectMapperFactory factory) {
return new JsonPath(this, getJsonPathConfig().jackson1ObjectMapperFactory(factory));
}
/**
* Configure JsonPath to use a specific Jackson 2 object mapper factory
*
* @param factory The Jackson 2 object mapper factory instance
* @return a new JsonPath instance
*/
public JsonPath using(Jackson2ObjectMapperFactory factory) {
return new JsonPath(this, getJsonPathConfig().jackson2ObjectMapperFactory(factory));
}
/**
* Configure JsonPath to with a specific JsonPathConfig.
*
* @param config The JsonPath config
* @return a new JsonPath instance
*/
public JsonPath using(JsonPathConfig config) {
return new JsonPath(this, config);
}
/**
* Syntactic sugar.
*
* @return The same JsonPath instance.
*/
public JsonPath and() {
return this;
}
/**
* Instantiate a new JsonPath instance.
*
* @param text The text containing the Object document
*/
public static JsonPath given(String text) {
return new JsonPath(text);
}
/**
* Instantiate a new JsonPath instance.
*
* @param stream The stream containing the Object document
*/
public static JsonPath given(InputStream stream) {
return new JsonPath(stream);
}
/**
* Instantiate a new JsonPath instance.
*
* @param file The file containing the Object document
*/
public static JsonPath given(File file) {
return new JsonPath(file);
}
/**
* Instantiate a new JsonPath instance.
*
* @param reader The reader containing the Object document
*/
public static JsonPath given(Reader reader) {
return new JsonPath(reader);
}
/**
* Instantiate a new JsonPath instance.
*
* @param url The URL containing the Object document
*/
public static JsonPath given(URL url) {
return new JsonPath(url);
}
/**
* Instantiate a new JsonPath instance.
*
* @param stream The stream containing the Object document
*/
public static JsonPath with(InputStream stream) {
return new JsonPath(stream);
}
/**
* Instantiate a new JsonPath instance.
*
* @param text The text containing the Object document
*/
public static JsonPath with(String text) {
return new JsonPath(text);
}
/**
* Instantiate a new JsonPath instance.
*
* @param file The file containing the Object document
*/
public static JsonPath with(File file) {
return new JsonPath(file);
}
/**
* Instantiate a new JsonPath instance.
*
* @param reader The reader containing the Object document
*/
public static JsonPath with(Reader reader) {
return new JsonPath(reader);
}
/**
* Instantiate a new JsonPath instance.
*
* @param url The URI containing the Object document
*/
public static JsonPath with(URL url) {
return new JsonPath(url);
}
/**
* Instantiate a new JsonPath instance.
*
* @param stream The stream containing the Object document
*/
public static JsonPath from(InputStream stream) {
return new JsonPath(stream);
}
/**
* Instantiate a new JsonPath instance.
*
* @param text The text containing the Object document
*/
public static JsonPath from(String text) {
return new JsonPath(text);
}
/**
* Instantiate a new JsonPath instance.
*
* @param file The file containing the Object document
*/
public static JsonPath from(File file) {
return new JsonPath(file);
}
/**
* Instantiate a new JsonPath instance.
*
* @param reader The reader containing the Object document
*/
public static JsonPath from(Reader reader) {
return new JsonPath(reader);
}
/**
* Instantiate a new JsonPath instance.
*
* @param url The URI containing the Object document
*/
public static JsonPath from(URL url) {
return new JsonPath(url);
}
/**
* Set the root path of the document so that you don't need to write the entire path. E.g.
* <pre>
* final JsonPath jsonPath = new JsonPath(Object).setRoot("store.book");
* assertThat(jsonPath.getInt("size()"), equalTo(4));
* assertThat(jsonPath.getList("author", String.class), hasItem("J. R. R. Tolkien"));
* </pre>
*
* @param rootPath The root path to use.
* @deprecated Use {@link #setRootPath(String)} instead
*/
@Deprecated
public JsonPath setRoot(String rootPath) {
return setRootPath(rootPath);
}
/**
* Set the root path of the document so that you don't need to write the entire path. E.g.
* <pre>
* final JsonPath jsonPath = new JsonPath(Object).setRootPath("store.book");
* assertThat(jsonPath.getInt("size()"), equalTo(4));
* assertThat(jsonPath.getList("author", String.class), hasItem("J. R. R. Tolkien"));
* </pre>
*
* @param rootPath The root path to use.
*/
public JsonPath setRootPath(String rootPath) {
AssertParameter.notNull(rootPath, "Root path");
this.rootPath = rootPath;
return this;
}
private JsonParser parseInputStream(final InputStream stream) {
return new JsonParser() {
@Override
public Object doParseWith(final ConfigurableJsonSlurper slurper) {
return new ExceptionCatcher() {
protected Object method() throws Exception {
return slurper.parse(toReader(stream));
}
}.invoke();
}
};
}
private JsonParser parseReader(final Reader reader) {
return new JsonParser() {
@Override
public Object doParseWith(final ConfigurableJsonSlurper slurper) {
return new ExceptionCatcher() {
protected Object method() throws Exception {
return slurper.parse(reader);
}
}.invoke();
}
};
}
private JsonParser parseFile(final File file) {
return new JsonParser() {
@Override
public Object doParseWith(final ConfigurableJsonSlurper slurper) {
return new ExceptionCatcher() {
protected Object method() throws Exception {
return slurper.parse(new FileReader(file));
}
}.invoke();
}
};
}
private JsonParser parseText(final String text) {
return new JsonParser() {
@Override
public Object doParseWith(final ConfigurableJsonSlurper slurper) {
return new ExceptionCatcher() {
protected Object method() throws Exception {
return slurper.parseText(text);
}
}.invoke();
}
};
}
private JsonParser parseURL(final URL url) {
return new JsonParser() {
@Override
public Object doParseWith(final ConfigurableJsonSlurper slurper) {
return new ExceptionCatcher() {
protected Object method() throws Exception {
return slurper.parse(toReader(url.openStream()));
}
}.invoke();
}
};
}
private BufferedReader toReader(InputStream in) {
final JsonPathConfig cfg = getJsonPathConfig();
try {
return new BufferedReader(new InputStreamReader(in, cfg.charset()));
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("Charset is invalid", e);
}
}
private abstract class ExceptionCatcher {
protected abstract Object method() throws Exception;
public Object invoke() {
try {
return method();