1 package us.codecraft.webmagic.selector;
2
3
4 import java.util.ArrayList;
5 import java.util.List;
6 import java.util.Map;
7 import com.alibaba.fastjson.JSON;
8 import com.jayway.jsonpath.JsonPath;
9
10
11
12
13
14
15
16
17 public class JsonPathSelector implements Selector {
18
19 private final String jsonPathStr;
20
21 private final JsonPath jsonPath;
22
23 public JsonPathSelector(String jsonPathStr) {
24 this.jsonPathStr = jsonPathStr;
25 this.jsonPath = JsonPath.compile(this.jsonPathStr);
26 }
27
28 @SuppressWarnings("unused")
29 public String getJsonPathStr() {
30 return jsonPathStr;
31 }
32
33 @Override
34 public String select(String text) {
35 Object object = jsonPath.read(text);
36 if (object == null) {
37 return null;
38 }
39 if (object instanceof List) {
40 List<?> list = (List<?>) object;
41 if (list.size() > 0) {
42 return toString(list.iterator().next());
43 }
44 }
45 return object.toString();
46 }
47
48 private String toString(Object object) {
49 if (object instanceof Map) {
50 return JSON.toJSONString(object);
51 } else {
52 return String.valueOf(object);
53 }
54 }
55
56 @Override
57 @SuppressWarnings("unchecked")
58 public List<String> selectList(String text) {
59 List<String> list = new ArrayList<>();
60 Object object = jsonPath.read(text);
61 if (object == null) {
62 return list;
63 }
64 if (object instanceof List) {
65 List<Object> items = (List<Object>) object;
66 for (Object item : items) {
67 list.add(toString(item));
68 }
69 } else {
70 list.add(toString(object));
71 }
72 return list;
73 }
74 }