Java - Jayway JsonPath

继续 json 系列:

GitHub Java JsonPath Star 最多的:Jayway JsonPath

https://github.com/json-path/JsonPath

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
package com.tracenote.Utils.Json;

import com.jayway.jsonpath.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.jayway.jsonpath.JsonPath.parse;
import static com.jayway.jsonpath.Criteria.where;
import static com.jayway.jsonpath.Filter.filter;
import static com.jayway.jsonpath.JsonPath.using;

public class JsonPathUtil {
public static void main(String[] args) {
String json = "{\n" +
" \"store\": {\n" +
" \"book\": [\n" +
" {\n" +
" \"category\": \"reference\",\n" +
" \"author\": \"Nigel Rees\",\n" +
" \"title\": \"Sayings of the Century\",\n" +
" \"price\": 8.95\n" +
" },\n" +
" {\n" +
" \"category\": \"fiction\",\n" +
" \"author\": \"Evelyn Waugh\",\n" +
" \"title\": \"Sword of Honour\",\n" +
" \"price\": 12.99\n" +
" },\n" +
" {\n" +
" \"category\": \"fiction\",\n" +
" \"author\": \"Herman Melville\",\n" +
" \"title\": \"Moby Dick\",\n" +
" \"isbn\": \"0-553-21311-3\",\n" +
" \"price\": 8.99\n" +
" },\n" +
" {\n" +
" \"category\": \"fiction\",\n" +
" \"author\": \"J. R. R. Tolkien\",\n" +
" \"title\": \"The Lord of the Rings\",\n" +
" \"isbn\": \"0-395-19395-8\",\n" +
" \"price\": 22.99\n" +
" }\n" +
" ],\n" +
" \"bicycle\": {\n" +
" \"color\": \"red\",\n" +
" \"price\": 19.95\n" +
" }\n" +
" },\n" +
" \"expensive\": 10\n" +
"}";

List<String> authors = JsonPath.read(json, "$.store.book[*].author");
System.out.println("authors: " + authors);

/**
* If you only want to read once this is OK.
* In case you need to read an other path as well this is not the way to go
* since the document will be parsed every time you call JsonPath.read(...).
* To avoid the problem you can parse the json first.
*/
Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);

String author0 = JsonPath.read(document, "$.store.book[0].author");
String author1 = JsonPath.read(document, "$.store.book[1].author");
System.out.println(author0);
System.out.println(author1);

/**
* By default a simple object mapper is provided by the MappingProvider SPI.
* This allows you to specify the return type you want
* and the MappingProvider will try to perform the mapping.
*/
String dataJson = "{\"date_as_long\" : 1605022303000}";
Date date = JsonPath.parse(dataJson).read("$['date_as_long']", Date.class);
System.out.println(date);


/**
* If you configure JsonPath to use JacksonMappingProvider or GsonMappingProvider
* you can even map your JsonPath output directly into POJO's.
*/
// Book book = JsonPath.parse(json).read("$.store.book[0]", Book.class);

/**
* To obtain full generics type information, use TypeRef.
* 有报错?用到时再解决吧……
*/
// TypeRef<List<String>> typeRef = new TypeRef<List<String>>() {};
// List<String> titles = JsonPath.parse(json).read("$.store.book[*].title", typeRef);
// System.out.println(titles);

/**
* Inline Predicates
*/
List<Map<String, Object>> books = JsonPath.parse(json)
.read("$.store.book[?(@.price < 10)]");
System.out.println(books);

/**
* Filter Predicates
*/
Filter cheapFictionFilter = filter(
where("category").is("fiction").and("price").lte(10D)
);

List<Map<String, Object>> books2 =
parse(json).read("$.store.book[?]", cheapFictionFilter);
System.out.println(books2);

// Filters can also be combined with 'OR' and 'AND'
Filter fooOrBar = filter(
where("foo").exists(true)).or(where("bar").exists(true)
);
Filter fooAndBar = filter(
where("foo").exists(true)).and(where("bar").exists(true)
);

/**
* Roll your own predicates
*/
Predicate booksWithISBN = new Predicate() {
@Override
public boolean apply(Predicate.PredicateContext ctx) {
return ctx.item(Map.class).containsKey("isbn");
}
};
List<Map<String, Object>> books3 =
parse(json).read("$.store.book[?].isbn", List.class, booksWithISBN);
System.out.println(books3);

/**
* Path vs Value
*/
Configuration conf = Configuration.builder()
.options(Option.AS_PATH_LIST).build();

List<String> pathList = using(conf).parse(json).read("$..author");

assertThat(pathList).containsExactly(
"$['store']['book'][0]['author']",
"$['store']['book'][1]['author']",
"$['store']['book'][2]['author']",
"$['store']['book'][3]['author']");

/**
* Set a value
*/
String newJson = JsonPath.parse(json).set("$['store']['book'][0]['author']", "Paul").jsonString();
System.out.println(newJson);


/**
* DEFAULT_PATH_LEAF_TO_NULL
* This option makes JsonPath return null for missing leafs. Consider the following json
*/
String json1 = "[\n" +
" {\n" +
" \"name\" : \"john\",\n" +
" \"gender\" : \"male\"\n" +
" },\n" +
" {\n" +
" \"name\" : \"ben\"\n" +
" }\n" +
"]";
Configuration conf = Configuration.defaultConfiguration();

//Works fine
String gender0 = JsonPath.using(conf).parse(json).read("$[0]['gender']");
//PathNotFoundException thrown
// String gender1 = JsonPath.using(conf).parse(json).read("$[1]['gender']");

Configuration conf2 = conf.addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);
//Works fine
String genderA = JsonPath.using(conf2).parse(json).read("$[0]['gender']");
//Works fine (null is returned)
String genderB = JsonPath.using(conf2).parse(json).read("$[1]['gender']");

/**
* ALWAYS_RETURN_LIST
* This option configures JsonPath to return a list even when the path is definite.
*/
Configuration conf3 = Configuration.defaultConfiguration();

//ClassCastException thrown
List<String> genders0 = JsonPath.using(conf).parse(json).read("$[0]['gender']");

Configuration conf4 = conf.addOptions(Option.ALWAYS_RETURN_LIST);

//Works fine
List<String> gendersN0 = JsonPath.using(conf2).parse(json).read("$[0]['gender']");

/**
* 更多参考 https://github.com/json-path/JsonPath
*/
}
}