/
JSONPath.java
4316 lines (3574 loc) · 145 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
package com.alibaba.fastjson;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.parser.JSONLexer;
import com.alibaba.fastjson.parser.JSONLexerBase;
import com.alibaba.fastjson.parser.JSONToken;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.parser.deserializer.FieldDeserializer;
import com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.serializer.FieldSerializer;
import com.alibaba.fastjson.serializer.JavaBeanSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.util.IOUtils;
import com.alibaba.fastjson.util.TypeUtils;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author wenshao[szujobs@hotmail.com]
* @since 1.2.0
*/
public class JSONPath implements JSONAware {
private static ConcurrentMap<String, JSONPath> pathCache = new ConcurrentHashMap<String, JSONPath>(128, 0.75f, 1);
private final String path;
private Segment[] segments;
private boolean hasRefSegment;
private SerializeConfig serializeConfig;
private ParserConfig parserConfig;
private boolean ignoreNullValue;
public JSONPath(String path){
this(path, SerializeConfig.getGlobalInstance(), ParserConfig.getGlobalInstance(), true);
}
public JSONPath(String path, boolean ignoreNullValue){
this(path, SerializeConfig.getGlobalInstance(), ParserConfig.getGlobalInstance(), ignoreNullValue);
}
public JSONPath(String path, SerializeConfig serializeConfig, ParserConfig parserConfig, boolean ignoreNullValue){
if (path == null || path.length() == 0) {
throw new JSONPathException("json-path can not be null or empty");
}
this.path = path;
this.serializeConfig = serializeConfig;
this.parserConfig = parserConfig;
this.ignoreNullValue = ignoreNullValue;
}
protected void init() {
if (segments != null) {
return;
}
if ("*".equals(path)) {
this.segments = new Segment[] { WildCardSegment.instance };
} else {
JSONPathParser parser = new JSONPathParser(path);
this.segments = parser.explain();
this.hasRefSegment = parser.hasRefSegment;
}
}
public boolean isRef() {
try {
init();
for (int i = 0; i < segments.length; ++i) {
Segment segment = segments[i];
Class segmentType = segment.getClass();
if (segmentType == ArrayAccessSegment.class
|| segmentType == PropertySegment.class) {
continue;
}
return false;
}
return true;
} catch (JSONPathException ex) {
// skip
return false;
}
}
public Object eval(Object rootObject) {
if (rootObject == null) {
return null;
}
init();
Object currentObject = rootObject;
for (int i = 0; i < segments.length; ++i) {
Segment segment = segments[i];
currentObject = segment.eval(this, rootObject, currentObject);
}
return currentObject;
}
public Object extract(DefaultJSONParser parser) {
if (parser == null) {
return null;
}
init();
if (hasRefSegment) {
Object root = parser.parse();
return this.eval(root);
}
if (segments.length == 0) {
return parser.parse();
}
Segment lastSegment = segments[segments.length - 1];
if (lastSegment instanceof TypeSegment
|| lastSegment instanceof FloorSegment
|| lastSegment instanceof MultiIndexSegment) {
return eval(
parser.parse());
}
Context context = null;
for (int i = 0; i < segments.length; ++i) {
Segment segment = segments[i];
boolean last = i == segments.length - 1;
if (context != null && context.object != null) {
context.object = segment.eval(this, null, context.object);
continue;
}
boolean eval;
if (!last) {
Segment nextSegment = segments[i + 1];
if (segment instanceof PropertySegment
&& ((PropertySegment) segment).deep
&& (nextSegment instanceof ArrayAccessSegment
|| nextSegment instanceof MultiIndexSegment
|| nextSegment instanceof MultiPropertySegment
|| nextSegment instanceof SizeSegment
|| nextSegment instanceof PropertySegment
|| nextSegment instanceof FilterSegment))
{
eval = true;
} else if (nextSegment instanceof ArrayAccessSegment
&& ((ArrayAccessSegment) nextSegment).index < 0) {
eval = true;
} else if (nextSegment instanceof FilterSegment) {
eval = true;
} else if (segment instanceof WildCardSegment) {
eval = true;
}else if(segment instanceof MultiIndexSegment){
eval = true;
} else {
eval = false;
}
} else {
eval = true;
}
context = new Context(context, eval);
segment.extract(this, parser, context);
}
return context.object;
}
private static class Context {
final Context parent;
final boolean eval;
Object object;
public Context(Context parent, boolean eval) {
this.parent = parent;
this.eval = eval;
}
}
public boolean contains(Object rootObject) {
if (rootObject == null) {
return false;
}
init();
Object currentObject = rootObject;
for (int i = 0; i < segments.length; ++i) {
Object parentObject = currentObject;
currentObject = segments[i].eval(this, rootObject, currentObject);
if (currentObject == null) {
return false;
}
if (currentObject == Collections.EMPTY_LIST && parentObject instanceof List) {
return ((List) parentObject).contains(currentObject);
}
}
return true;
}
@SuppressWarnings("rawtypes")
public boolean containsValue(Object rootObject, Object value) {
Object currentObject = eval(rootObject);
if (currentObject == value) {
return true;
}
if (currentObject == null) {
return false;
}
if (currentObject instanceof Iterable) {
Iterator it = ((Iterable) currentObject).iterator();
while (it.hasNext()) {
Object item = it.next();
if (eq(item, value)) {
return true;
}
}
return false;
}
return eq(currentObject, value);
}
public int size(Object rootObject) {
if (rootObject == null) {
return -1;
}
init();
Object currentObject = rootObject;
for (int i = 0; i < segments.length; ++i) {
currentObject = segments[i].eval(this, rootObject, currentObject);
}
return evalSize(currentObject);
}
/**
* Extract keySet or field names from rootObject on this JSONPath.
*
* @param rootObject Can be a map or custom object. Array and Collection are not supported.
* @return Set of keys, or <code>null</code> if not supported.
*/
public Set<?> keySet(Object rootObject) {
if (rootObject == null) {
return null;
}
init();
Object currentObject = rootObject;
for (int i = 0; i < segments.length; ++i) {
currentObject = segments[i].eval(this, rootObject, currentObject);
}
return evalKeySet(currentObject);
}
public void patchAdd(Object rootObject, Object value, boolean replace) {
if (rootObject == null) {
return;
}
init();
Object currentObject = rootObject;
Object parentObject = null;
for (int i = 0; i < segments.length; ++i) {
parentObject = currentObject;
Segment segment = segments[i];
currentObject = segment.eval(this, rootObject, currentObject);
if (currentObject == null && i != segments.length - 1) {
if (segment instanceof PropertySegment) {
currentObject = new JSONObject();
((PropertySegment) segment).setValue(this, parentObject, currentObject);
}
}
}
Object result = currentObject;
if ((!replace) && result instanceof Collection) {
Collection collection = (Collection) result;
collection.add(value);
return;
}
Object newResult;
if (result != null && !replace) {
Class<?> resultClass = result.getClass();
if (resultClass.isArray()) {
int length = Array.getLength(result);
Object descArray = Array.newInstance(resultClass.getComponentType(), length + 1);
System.arraycopy(result, 0, descArray, 0, length);
Array.set(descArray, length, value);
newResult = descArray;
}
else if (Map.class.isAssignableFrom(resultClass)) {
newResult = value;
} else {
throw new JSONException("unsupported array put operation. " + resultClass);
}
} else {
newResult = value;
}
Segment lastSegment = segments[segments.length - 1];
if (lastSegment instanceof PropertySegment) {
PropertySegment propertySegment = (PropertySegment) lastSegment;
propertySegment.setValue(this, parentObject, newResult);
return;
}
if (lastSegment instanceof ArrayAccessSegment) {
((ArrayAccessSegment) lastSegment).setValue(this, parentObject, newResult);
return;
}
throw new UnsupportedOperationException();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void arrayAdd(Object rootObject, Object... values) {
if (values == null || values.length == 0) {
return;
}
if (rootObject == null) {
return;
}
init();
Object currentObject = rootObject;
Object parentObject = null;
for (int i = 0; i < segments.length; ++i) {
if (i == segments.length - 1) {
parentObject = currentObject;
}
currentObject = segments[i].eval(this, rootObject, currentObject);
}
Object result = currentObject;
if (result == null) {
throw new JSONPathException("value not found in path " + path);
}
if (result instanceof Collection) {
Collection collection = (Collection) result;
for (Object value : values) {
collection.add(value);
}
return;
}
Class<?> resultClass = result.getClass();
Object newResult;
if (resultClass.isArray()) {
int length = Array.getLength(result);
Object descArray = Array.newInstance(resultClass.getComponentType(), length + values.length);
System.arraycopy(result, 0, descArray, 0, length);
for (int i = 0; i < values.length; ++i) {
Array.set(descArray, length + i, values[i]);
}
newResult = descArray;
} else {
throw new JSONException("unsupported array put operation. " + resultClass);
}
Segment lastSegment = segments[segments.length - 1];
if (lastSegment instanceof PropertySegment) {
PropertySegment propertySegment = (PropertySegment) lastSegment;
propertySegment.setValue(this, parentObject, newResult);
return;
}
if (lastSegment instanceof ArrayAccessSegment) {
((ArrayAccessSegment) lastSegment).setValue(this, parentObject, newResult);
return;
}
throw new UnsupportedOperationException();
}
public boolean remove(Object rootObject) {
if (rootObject == null) {
return false;
}
init();
Object currentObject = rootObject;
Object parentObject = null;
Segment lastSegment = segments[segments.length - 1];
for (int i = 0; i < segments.length; ++i) {
if (i == segments.length - 1) {
parentObject = currentObject;
break;
}
Segment segement = segments[i];
if (i == segments.length - 2
&& lastSegment instanceof FilterSegment
&& segement instanceof PropertySegment
) {
FilterSegment filterSegment = (FilterSegment) lastSegment;
if (currentObject instanceof List) {
PropertySegment propertySegment = (PropertySegment) segement;
List list = (List) currentObject;
for (Iterator it = list.iterator();it.hasNext();) {
Object item = it.next();
Object result = propertySegment.eval(this, rootObject, item);
if (result instanceof Iterable) {
filterSegment.remove(this, rootObject, result);
} else if (result instanceof Map) {
if (filterSegment.filter.apply(this, rootObject, currentObject, result)) {
it.remove();
}
}
}
return true;
} else if (currentObject instanceof Map) {
PropertySegment propertySegment = (PropertySegment) segement;
Object result = propertySegment.eval(this, rootObject, currentObject);
if (result == null) {
return false;
}
if (result instanceof Map
&& filterSegment.filter.apply(this, rootObject, currentObject, result)) {
propertySegment.remove(this, currentObject);
return true;
}
}
}
currentObject = segement.eval(this, rootObject, currentObject);
if (currentObject == null) {
break;
}
}
if (parentObject == null) {
return false;
}
if (lastSegment instanceof PropertySegment) {
PropertySegment propertySegment = (PropertySegment) lastSegment;
if (parentObject instanceof Collection) {
if (segments.length > 1) {
Segment parentSegment = segments[segments.length - 2];
if (parentSegment instanceof RangeSegment || parentSegment instanceof MultiIndexSegment) {
Collection collection = (Collection) parentObject;
boolean removedOnce = false;
for (Object item : collection) {
boolean removed = propertySegment.remove(this, item);
if (removed) {
removedOnce = true;
}
}
return removedOnce;
}
}
}
return propertySegment.remove(this, parentObject);
}
if (lastSegment instanceof ArrayAccessSegment) {
return ((ArrayAccessSegment) lastSegment).remove(this, parentObject);
}
if (lastSegment instanceof FilterSegment) {
FilterSegment filterSegment = (FilterSegment) lastSegment;
return filterSegment.remove(this, rootObject, parentObject);
}
throw new UnsupportedOperationException();
}
public boolean set(Object rootObject, Object value) {
return set(rootObject, value, true);
}
public boolean set(Object rootObject, Object value, boolean p) {
if (rootObject == null) {
return false;
}
init();
Object currentObject = rootObject;
Object parentObject = null;
for (int i = 0; i < segments.length; ++i) {
// if (i == segments.length - 1) {
// parentObject = currentObject;
// break;
// }
//
parentObject = currentObject;
Segment segment = segments[i];
currentObject = segment.eval(this, rootObject, currentObject);
if (currentObject == null) {
Segment nextSegment = null;
if (i < segments.length - 1) {
nextSegment = segments[i + 1];
}
Object newObj = null;
if (nextSegment instanceof PropertySegment) {
JavaBeanDeserializer beanDeserializer = null;
Class<?> fieldClass = null;
if (segment instanceof PropertySegment) {
String propertyName = ((PropertySegment) segment).propertyName;
Class<?> parentClass = parentObject.getClass();
JavaBeanDeserializer parentBeanDeserializer = getJavaBeanDeserializer(parentClass);
if (parentBeanDeserializer != null) {
FieldDeserializer fieldDeserializer = parentBeanDeserializer.getFieldDeserializer(propertyName);
fieldClass = fieldDeserializer.fieldInfo.fieldClass;
beanDeserializer = getJavaBeanDeserializer(fieldClass);
}
}
if (beanDeserializer != null) {
if (beanDeserializer.beanInfo.defaultConstructor != null) {
newObj = beanDeserializer.createInstance(null, fieldClass);
} else {
return false;
}
} else {
newObj = new JSONObject();
}
} else if (nextSegment instanceof ArrayAccessSegment) {
newObj = new JSONArray();
}
if (newObj != null) {
if (segment instanceof PropertySegment) {
PropertySegment propSegement = (PropertySegment) segment;
propSegement.setValue(this, parentObject, newObj);
currentObject = newObj;
continue;
} else if (segment instanceof ArrayAccessSegment) {
ArrayAccessSegment arrayAccessSegement = (ArrayAccessSegment) segment;
arrayAccessSegement.setValue(this, parentObject, newObj);
currentObject = newObj;
continue;
}
}
break;
}
}
if (parentObject == null) {
return false;
}
Segment lastSegment = segments[segments.length - 1];
if (lastSegment instanceof PropertySegment) {
PropertySegment propertySegment = (PropertySegment) lastSegment;
propertySegment.setValue(this, parentObject, value);
return true;
}
if (lastSegment instanceof ArrayAccessSegment) {
return ((ArrayAccessSegment) lastSegment).setValue(this, parentObject, value);
}
throw new UnsupportedOperationException();
}
public static Object eval(Object rootObject, String path) {
JSONPath jsonpath = compile(path);
return jsonpath.eval(rootObject);
}
public static Object eval(Object rootObject, String path, boolean ignoreNullValue) {
JSONPath jsonpath = compile(path, ignoreNullValue);
return jsonpath.eval(rootObject);
}
public static int size(Object rootObject, String path) {
JSONPath jsonpath = compile(path);
Object result = jsonpath.eval(rootObject);
return jsonpath.evalSize(result);
}
/**
* Compile jsonPath and use it to extract keySet or field names from rootObject.
*
* @param rootObject Can be a map or custom object. Array and Collection are not supported.
* @param path JSONPath string to be compiled.
* @return Set of keys, or <code>null</code> if not supported.
*/
public static Set<?> keySet(Object rootObject, String path) {
JSONPath jsonpath = compile(path);
Object result = jsonpath.eval(rootObject);
return jsonpath.evalKeySet(result);
}
public static boolean contains(Object rootObject, String path) {
if (rootObject == null) {
return false;
}
JSONPath jsonpath = compile(path);
return jsonpath.contains(rootObject);
}
public static boolean containsValue(Object rootObject, String path, Object value) {
JSONPath jsonpath = compile(path);
return jsonpath.containsValue(rootObject, value);
}
public static void arrayAdd(Object rootObject, String path, Object... values) {
JSONPath jsonpath = compile(path);
jsonpath.arrayAdd(rootObject, values);
}
public static boolean set(Object rootObject, String path, Object value) {
JSONPath jsonpath = compile(path);
return jsonpath.set(rootObject, value);
}
public static boolean remove(Object root, String path) {
JSONPath jsonpath = compile(path);
return jsonpath.remove(root);
}
public static JSONPath compile(String path) {
if (path == null) {
throw new JSONPathException("jsonpath can not be null");
}
JSONPath jsonpath = pathCache.get(path);
if (jsonpath == null) {
jsonpath = new JSONPath(path);
if (pathCache.size() < 1024) {
pathCache.putIfAbsent(path, jsonpath);
jsonpath = pathCache.get(path);
}
}
return jsonpath;
}
public static JSONPath compile(String path, boolean ignoreNullValue) {
if (path == null) {
throw new JSONPathException("jsonpath can not be null");
}
JSONPath jsonpath = pathCache.get(path);
if (jsonpath == null) {
jsonpath = new JSONPath(path, ignoreNullValue);
if (pathCache.size() < 1024) {
pathCache.putIfAbsent(path, jsonpath);
jsonpath = pathCache.get(path);
}
}
return jsonpath;
}
/**
* @since 1.2.9
* @param json
* @param path
* @return
*/
public static Object read(String json, String path) {
return compile(path)
.eval(
JSON.parse(json)
);
}
/**
* @since 1.2.51
* @param json
* @param path
* @return
*/
public static Object extract(String json, String path, ParserConfig config, int features, Feature... optionFeatures) {
features |= Feature.OrderedField.mask;
DefaultJSONParser parser = new DefaultJSONParser(json, config, features);
JSONPath jsonPath = compile(path);
Object result = jsonPath.extract(parser);
parser.lexer.close();
return result;
}
public static Object extract(String json, String path) {
return extract(json, path, ParserConfig.global, JSON.DEFAULT_PARSER_FEATURE);
}
public static Map<String, Object> paths(Object javaObject) {
return paths(javaObject, SerializeConfig.globalInstance);
}
public static Map<String, Object> paths(Object javaObject, SerializeConfig config) {
Map<Object, String> values = new IdentityHashMap<Object, String>();
Map<String, Object> paths = new HashMap<String, Object>();
paths(values, paths, "/", javaObject, config);
return paths;
}
private static void paths(Map<Object, String> values, Map<String, Object> paths, String parent, Object javaObject, SerializeConfig config) {
if (javaObject == null) {
return;
}
String p = values.put(javaObject, parent);
if (p != null) {
Class<?> type = javaObject.getClass();
boolean basicType = type == String.class
|| type == Boolean.class
|| type == Character.class
|| type == UUID.class
|| type.isEnum()
|| javaObject instanceof Number
|| javaObject instanceof Date
;
if (!basicType) {
return;
}
}
paths.put(parent, javaObject);
if (javaObject instanceof Map) {
Map map = (Map) javaObject;
for (Object entryObj : map.entrySet()) {
Map.Entry entry = (Map.Entry) entryObj;
Object key = entry.getKey();
if (key instanceof String) {
String path = parent.equals("/") ? "/" + key : parent + "/" + key;
paths(values, paths, path, entry.getValue(), config);
}
}
return;
}
if (javaObject instanceof Collection) {
Collection collection = (Collection) javaObject;
int i = 0;
for (Object item : collection) {
String path = parent.equals("/") ? "/" + i : parent + "/" + i;
paths(values, paths, path, item, config);
++i;
}
return;
}
Class<?> clazz = javaObject.getClass();
if (clazz.isArray()) {
int len = Array.getLength(javaObject);
for (int i = 0; i < len; ++i) {
Object item = Array.get(javaObject, i);
String path = parent.equals("/") ? "/" + i : parent + "/" + i;
paths(values, paths, path, item, config);
}
return;
}
if (ParserConfig.isPrimitive2(clazz) || clazz.isEnum()) {
return;
}
ObjectSerializer serializer = config.getObjectWriter(clazz);
if (serializer instanceof JavaBeanSerializer) {
JavaBeanSerializer javaBeanSerializer = (JavaBeanSerializer) serializer;
try {
Map<String, Object> fieldValues = javaBeanSerializer.getFieldValuesMap(javaObject);
for (Map.Entry<String, Object> entry : fieldValues.entrySet()) {
String key = entry.getKey();
if (key instanceof String) {
String path = parent.equals("/") ? "/" + key : parent + "/" + key;
paths(values, paths, path, entry.getValue(), config);
}
}
} catch (Exception e) {
throw new JSONException("toJSON error", e);
}
return;
}
return;
}
public String getPath() {
return path;
}
static class JSONPathParser {
private final String path;
private int pos;
private char ch;
private int level;
private boolean hasRefSegment;
private static final String strArrayRegex = "\'\\s*,\\s*\'";
private static final Pattern strArrayPatternx = Pattern.compile(strArrayRegex);
public JSONPathParser(String path){
this.path = path;
next();
}
void next() {
ch = path.charAt(pos++);
}
char getNextChar() {
return path.charAt(pos);
}
boolean isEOF() {
return pos >= path.length();
}
Segment readSegement() {
if (level == 0 && path.length() == 1) {
if (isDigitFirst(ch)) {
int index = ch - '0';
return new ArrayAccessSegment(index);
} else if ((ch >= 'a' && ch <= 'z') || ((ch >= 'A' && ch <= 'Z'))) {
return new PropertySegment(Character.toString(ch), false);
}
}
while (!isEOF()) {
skipWhitespace();
if (ch == '$') {
next();
skipWhitespace();
if (ch == '?') {
return new FilterSegment(
(Filter) parseArrayAccessFilter(false));
}
continue;
}
if (ch == '.' || ch == '/') {
int c0 = ch;
boolean deep = false;
next();
if (c0 == '.' && ch == '.') {
next();
deep = true;
if (path.length() > pos + 3
&& ch == '['
&& path.charAt(pos) == '*'
&& path.charAt(pos + 1) == ']'
&& path.charAt(pos + 2) == '.') {
next();
next();
next();
next();
}
}
if (ch == '*' || (deep && ch == '[')) {
boolean objectOnly = ch == '[';
if (!isEOF()) {
next();
}
if (deep) {
if (objectOnly) {
return WildCardSegment.instance_deep_objectOnly;
} else {
return WildCardSegment.instance_deep;
}
} else {
return WildCardSegment.instance;
}
}
if (isDigitFirst(ch)) {
return parseArrayAccess(false);
}
String propertyName = readName();
if (ch == '(') {
next();
if (ch == ')') {
if (!isEOF()) {
next();
}
if ("size".equals(propertyName) || "length".equals(propertyName)) {
return SizeSegment.instance;
} else if ("max".equals(propertyName)) {
return MaxSegment.instance;
} else if ("min".equals(propertyName)) {
return MinSegment.instance;
} else if ("keySet".equals(propertyName)) {
return KeySetSegment.instance;
} else if ("type".equals(propertyName)) {
return TypeSegment.instance;
} else if ("floor".equals(propertyName)) {
return FloorSegment.instance;
}
throw new JSONPathException("not support jsonpath : " + path);
}
throw new JSONPathException("not support jsonpath : " + path);
}
return new PropertySegment(propertyName, deep);
}
if (ch == '[') {
return parseArrayAccess(true);
}
if (level == 0) {
String propertyName = readName();
return new PropertySegment(propertyName, false);
}
if (ch == '?') {
return new FilterSegment(
(Filter) parseArrayAccessFilter(false));
}
throw new JSONPathException("not support jsonpath : " + path);
}
return null;
}
public final void skipWhitespace() {
for (;;) {
if (ch <= ' ' && (ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t' || ch == '\f' || ch == '\b')) {
next();
continue;
} else {
break;
}
}
}
Segment parseArrayAccess(boolean acceptBracket) {