JsonPath是一種簡單的方法來提取給定JSON文檔的部分內容。 JsonPath有許多編程語言,如Javascript,Python和PHP,Java。
JsonPath提供的json解析非常強大,它提供了類似正則表達式的語法,基本上可以滿足所有你想要獲得的json內容。下面我把官網介紹的每個表達式用代碼實現,可以更直觀的知道該怎麼用它。
GitHub:https://github.com/json-path/JsonPath
以下是從GitHub中用我蹩腳的英格利希,翻譯過來的,將就着看吧,推薦去管網上面閱讀。
JsonPath可在Central Maven存儲庫中找到。 Maven用戶將其添加到您的POM。
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>
如果您需要幫助,請在Stack Overflow中提問。 標記問題'jsonpath'和'java'。
JsonPath表達式總是以與XPath表達式結合使用XML文檔相同的方式引用JSON結構。
JsonPath中的“根成員對象”始終稱爲$,無論是對象還是數組。
JsonPath表達式可以使用點表示法
$.store.book [0].title
或括號表示法
$['store']['book'][0]['title']
操作符
操作 | 說明 |
---|---|
$ |
查詢根元素。這將啓動所有路徑表達式。 |
@ |
當前節點由過濾謂詞處理。 |
* |
通配符,必要時可用任何地方的名稱或數字。 |
.. |
深層掃描。 必要時在任何地方可以使用名稱。 |
.<name> |
點,表示子節點 |
['<name>' (, '<name>')] |
括號表示子項 |
[<number> (, <number>)] |
數組索引或索引 |
[start:end] |
數組切片操作 |
[?(<expression>)] |
過濾表達式。 表達式必須求值爲一個布爾值。 |
函數
函數可以在路徑的尾部調用,函數的輸出是路徑表達式的輸出,該函數的輸出是由函數本身所決定的。
函數 | 描述 | 輸出 |
---|---|---|
min() |
提供數字數組的最小值 | Double |
max() |
提供數字數組的最大值 | Double |
avg() |
提供數字數組的平均值 | Double |
stddev() |
提供數字數組的標準偏差值 | Double |
length() |
提供數組的長度 | Integer |
過濾器運算符
過濾器是用於篩選數組的邏輯表達式。一個典型的過濾器將是[?(@.age > 18)],其中@表示正在處理的當前項目。 可以使用邏輯運算符&&和||創建更復雜的過濾器。 字符串文字必須用單引號或雙引號括起來([?(@.color == 'blue')] 或者 [?(@.color == "blue")]).
操作符 | 描述 |
---|---|
== |
left等於right(注意1不等於'1') |
!= |
不等於 |
< |
小於 |
<= |
小於等於 |
> |
大於 |
>= |
大於等於 |
=~ |
匹配正則表達式[?(@.name =~ /foo.*?/i)] |
in |
左邊存在於右邊 [?(@.size in ['S', 'M'])] |
nin |
左邊不存在於右邊 |
size |
(數組或字符串)長度 |
empty |
(數組或字符串)爲空 |
Java操作示例
JSON Demo
{
"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
}
},
"expensive": 10
}
JsonPath (點擊鏈接測試) | 結果 |
---|---|
$.store.book[*].author |
獲取json中store下book下的所有author值 |
$..author |
獲取所有json中所有author的值 |
$.store.* |
所有的東西,書籍和自行車 |
$.store..price |
獲取json中store下所有price的值 |
$..book[2] |
獲取json中book數組的第3個值 |
$..book[-2] |
倒數的第二本書 |
$..book[0,1] |
前兩本書 |
$..book[:2] |
從索引0(包括)到索引2(排除)的所有圖書 |
$..book[1:2] |
從索引1(包括)到索引2(排除)的所有圖書 |
$..book[-2:] |
獲取json中book數組的最後兩個值 |
$..book[2:] |
獲取json中book數組的第3個到最後一個的區間值 |
$..book[?(@.isbn)] |
獲取json中book數組中包含isbn的所有值 |
$.store.book[?(@.price < 10)] |
獲取json中book數組中price<10的所有值 |
$..book[?(@.price <= $['expensive'])] |
獲取json中book數組中price<=expensive的所有值 |
$..book[?(@.author =~ /.*REES/i)] |
獲取json中book數組中的作者以REES結尾的所有值(REES不區分大小寫) |
$..* |
逐層列出json中的所有值,層級由外到內 |
$..book.length() |
獲取json中book數組的長度 |
閱讀文檔
使用JsonPath的最簡單的最直接的方法是通過靜態讀取API。
String json = "...";
List<String> authors = JsonPath.read(json, "$.store.book[*].author");
如果你只想讀取一次,那麼上面的代碼就可以了。
如果你還想讀取其他路徑,現在上面不是很好的方法,因爲他每次獲取都需要再解析整個文檔。所以,我們可以先解析整個文檔,再選擇調用路徑。
String json = "...";
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");
JsonPath還提供流暢的API。 這也是最靈活的一個。
String json = "...";
ReadContext ctx = JsonPath.parse(json);
List<String> authorsOfBooksWithISBN = ctx.read("$.store.book[?(@.isbn)].author");
List<Map<String, Object>> expensiveBooks = JsonPath
.using(configuration)
.parse(json)
.read("$.store.book[?(@.price > 10)]", List.class);
何時返回
當在java中使用JsonPath時,重要的是要知道你在結果中期望什麼類型。 JsonPath將自動嘗試將結果轉換爲調用者預期的類型。
// 拋出 java.lang.ClassCastException 異常
List<String> list = JsonPath.parse(json).read("$.store.book[0].author")
// 正常
String author = JsonPath.parse(json).read("$.store.book[0].author")
當評估路徑時,你需要理解路徑確定的概念。路徑是不確定的,它包含
-
..
:深層掃描操作 -
?(<expression>)
:表達式 -
[<number>, <number> (, <number>)]
:多個數組索引
不確定的路徑總是返回一個列表(由當前的JsonProvider表示)。
默認情況下,MappingProvider SPI提供了一個簡單的對象映射器。 這允許您指定所需的返回類型,MappingProvider將嘗試執行映射。 在下面的示例中,演示了Long和Date之間的映射。
String json = "{\"date_as_long\" : 1411455611975}";
Date date = JsonPath.parse(json).read("$['date_as_long']", Date.class);
如果您將JsonPath配置爲使用JacksonMappingProvider或GsonMappingProvider,您甚至可以將JsonPath輸出直接映射到POJO中。
Book book = JsonPath.parse(json).read("$.store.book[0]", Book.class);
要獲取完整的泛型類型信息,請使用TypeRef。
TypeRef<List<String>> typeRef = new TypeRef<List<String>>(){};
List<String> titles = JsonPath.parse(JSON_DOCUMENT).read("$.store.book[*].title", typeRef);
謂詞
在JsonPath中創建過濾器謂詞有三種不同的方法。
內聯謂詞
內聯謂詞是路徑中定義的謂詞。
List<Map<String, Object>> books = JsonPath.parse(json).read("$.store.book[?(@.price < 10)]");
你可以使用 && 和 || 結合多個謂詞 [?(@.price < 10 && @.category == 'fiction')] , [?(@.category == 'reference' || @.price > 10)].
你也可以使用!否定一個謂詞 [?(!(@.price < 10 && @.category == 'fiction'))].
過濾謂詞
謂詞可以使用Filter API構建,如下所示:
import static com.jayway.jsonpath.JsonPath.parse;
import static com.jayway.jsonpath.Criteria.where;
import static com.jayway.jsonpath.Filter.filter;
...
...
Filter cheapFictionFilter = filter(
where("category").is("fiction").and("price").lte(10D)
);
List<Map<String, Object>> books = parse(json).read("$.store.book[?]", cheapFictionFilter);
注意佔位符? 爲路徑中的過濾器。 當提供多個過濾器時,它們按照佔位符數量與提供的過濾器數量相匹配的順序應用。 您可以在一個過濾器操作[?,?]中指定多個謂詞佔位符,這兩個謂詞都必須匹配。
過濾器也可以與“OR”和“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)
);
自定義
第三個選擇是實現你自己的謂詞
Predicate booksWithISBN = new Predicate() {
@Override
public boolean apply(PredicateContext ctx) {
return ctx.item(Map.class).containsKey("isbn");
}
};
List<Map<String, Object>> books = reader.read("$.store.book[?].isbn", List.class, booksWithISBN);
Path vs Value
在Goessner實現中,JsonPath可以返回Path或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']");
調整配置
選項創建配置時,有幾個可以改變默認行爲的選項標誌。
DEFAULT_PATH_LEAF_TO_NULL
此選項使JsonPath對於缺少的葉子返回null。考慮下面的Json:
[
{
"name" : "john",
"gender" : "male"
},
{
"name" : "ben"
}
]
Configuration conf = Configuration.defaultConfiguration();
// 正常
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);
// 正常
String gender0 = JsonPath.using(conf2).parse(json).read("$[0]['gender']");
// 正常 (返回 null)
String gender1 = JsonPath.using(conf2).parse(json).read("$[1]['gender']");
ALWAYS_RETURN_LIST
此選項配置JsonPath返回列表
Configuration conf = Configuration.defaultConfiguration();
// 正常
List<String> genders0 = JsonPath.using(conf).parse(json).read("$[0]['gender']");
// 異常 PathNotFoundException thrown
List<String> genders1 = JsonPath.using(conf).parse(json).read("$[1]['gender']");
SUPPRESS_EXCEPTIONS
該選項確保不會從路徑評估傳播異常。 遵循這些簡單的規則:
-
如果選項ALWAYS_RETURN_LIST存在,將返回一個空列表
-
如果選項ALWAYS_RETURN_LIST不存在返回null
JsonProvider SPI
JsonPath is shipped with three different JsonProviders:
-
JsonSmartJsonProvider
(default)
更改配置默認值只能在應用程序初始化時完成。 強烈不建議在運行時進行更改,尤其是在多線程應用程序中。
Configuration.setDefaults(new Configuration.Defaults() {
private final JsonProvider jsonProvider = new JacksonJsonProvider();
private final MappingProvider mappingProvider = new JacksonMappingProvider();
@Override
public JsonProvider jsonProvider() {
return jsonProvider;
}
@Override
public MappingProvider mappingProvider() {
return mappingProvider;
}
@Override
public Set<Option> options() {
return EnumSet.noneOf(Option.class);
}
});
請注意,JacksonJsonProvider需要com.fasterxml.jackson.core:jackson-databind:2.4.5,GsonJsonProvider需要在您的類路徑上使用com.google.code.gson:gson:2.3.1。
Cache SPI
在JsonPath 2.1.0中,引入了一種新的Cache SPI。 這允許API消費者以適合其需求的方式配置路徑緩存。 緩存必須在首次訪問之前配置,或者拋出JsonPathException
。 JsonPath附帶兩個緩存實現
-
com.jayway.jsonpath.spi.cache.LRUCache(默認,線程安全)
-
com.jayway.jsonpath.spi.cache.NOOPCache(無緩存)
如果要實現自己的緩存,API很簡單。
CacheProvider.setCache(new Cache() {
//Not thread safe simple cache
private Map<String, JsonPath> map = new HashMap<String, JsonPath>();
@Override
public JsonPath get(String key) {
return map.get(key);
}
@Override
public void put(String key, JsonPath jsonPath) {
map.put(key, jsonPath);
}
});
Java操作示例源碼
Json
{
"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": "JavaWeb",
"author": "X-rapido",
"title": "Top-link",
"isbn": "0-553-211231-3",
"price": 32.68
},
{
"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
}
},
"expensive": 10
}
Java1
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Iterator;
import java.util.List;
import com.jayway.jsonpath.JsonPath;
public class TestJsonPath {
public static void main(String[] args) {
String sjson = readtxt();
print("--------------------------------------getJsonValue--------------------------------------");
getJsonValue(sjson);
}
private static String readtxt() {
StringBuilder sb = new StringBuilder();
try {
FileReader fr = new FileReader("D:/books.txt");
BufferedReader bfd = new BufferedReader(fr);
String s = "";
while((s=bfd.readLine())!=null) {
sb.append(s);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(sb.toString());
return sb.toString();
}
private static void getJsonValue(String json) {
//The authors of all books:獲取json中store下book下的所有author值
List<String> authors1 = JsonPath.read(json, "$.store.book[*].author");
//All authors:獲取所有json中所有author的值
List<String> authors2 = JsonPath.read(json, "$..author");
//All things, both books and bicycles
//authors3返回的是net.minidev.json.JSONArray:獲取json中store下的所有value值,不包含key,如key有兩個,book和bicycle
List<Object> authors3 = JsonPath.read(json, "$.store.*");
//The price of everything:獲取json中store下所有price的值
List<Object> authors4 = JsonPath.read(json, "$.store..price");
//The third book:獲取json中book數組的第3個值
List<Object> authors5 = JsonPath.read(json, "$..book[2]");
//The first two books:獲取json中book數組的第1和第2兩個個值
List<Object> authors6 = JsonPath.read(json, "$..book[0,1]");
//All books from index 0 (inclusive) until index 2 (exclusive):獲取json中book數組的前兩個區間值
List<Object> authors7 = JsonPath.read(json, "$..book[:2]");
//All books from index 1 (inclusive) until index 2 (exclusive):獲取json中book數組的第2個值
List<Object> authors8 = JsonPath.read(json, "$..book[1:2]");
//Last two books:獲取json中book數組的最後兩個值
List<Object> authors9 = JsonPath.read(json, "$..book[-2:]");
//Book number two from tail:獲取json中book數組的第3個到最後一個的區間值
List<Object> authors10 = JsonPath.read(json, "$..book[2:]");
//All books with an ISBN number:獲取json中book數組中包含isbn的所有值
List<Object> authors11 = JsonPath.read(json, "$..book[?(@.isbn)]");
//All books in store cheaper than 10:獲取json中book數組中price<10的所有值
List<Object> authors12 = JsonPath.read(json, "$.store.book[?(@.price < 10)]");
//All books in store that are not "expensive":獲取json中book數組中price<=expensive的所有值
List<Object> authors13 = JsonPath.read(json, "$..book[?(@.price <= $['expensive'])]");
//All books matching regex (ignore case):獲取json中book數組中的作者以REES結尾的所有值(REES不區分大小寫)
List<Object> authors14 = JsonPath.read(json, "$..book[?(@.author =~ /.*REES/i)]");
//Give me every thing:逐層列出json中的所有值,層級由外到內
List<Object> authors15 = JsonPath.read(json, "$..*");
//The number of books:獲取json中book數組的長度
List<Object> authors16 = JsonPath.read(json, "$..book.length()");
print("**********authors1**********");
print(authors1);
print("**********authors2**********");
print(authors2);
print("**********authors3**********");
printOb(authors3);
print("**********authors4**********");
printOb(authors4);
print("**********authors5**********");
printOb(authors5);
print("**********authors6**********");
printOb(authors6);
print("**********authors7**********");
printOb(authors7);
print("**********authors8**********");
printOb(authors8);
print("**********authors9**********");
printOb(authors9);
print("**********authors10**********");
printOb(authors10);
print("**********authors11**********");
printOb(authors11);
print("**********authors12**********");
printOb(authors12);
print("**********authors13**********");
printOb(authors13);
print("**********authors14**********");
printOb(authors14);
print("**********authors15**********");
printOb(authors15);
print("**********authors16**********");
printOb(authors16);
}
private static void print(List<String> list) {
for(Iterator<String> it = list.iterator();it.hasNext();) {
System.out.println(it.next());
}
}
private static void printOb(List<Object> list) {
for(Iterator<Object> it = list.iterator();it.hasNext();) {
System.out.println(it.next());
}
}
private static void print(String s) {
System.out.println("\n"+s);
}
}
輸出
{"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":"JavaWeb","author":"X-rapido","title":"Top-link","isbn":"0-553-211231-3","price":32.68},{"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}},"expensive":10}
--------------------------------------getJsonValue--------------------------------------
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/D:/workSpaces/SupportPackge/MavenRepository/org/apache/logging/log4j/log4j-slf4j-impl/2.0.2/log4j-slf4j-impl-2.0.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/D:/workSpaces/SupportPackge/MavenRepository/org/slf4j/slf4j-log4j12/1.7.10/slf4j-log4j12-1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory]
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
**********authors1**********
Nigel Rees
Evelyn Waugh
Herman Melville
X-rapido
J. R. R. Tolkien
**********authors2**********
Nigel Rees
Evelyn Waugh
Herman Melville
X-rapido
J. R. R. Tolkien
**********authors3**********
[{"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":"JavaWeb","author":"X-rapido","title":"Top-link","isbn":"0-553-211231-3","price":32.68},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}]
{color=red, price=19.95}
**********authors4**********
8.95
12.99
8.99
32.68
22.99
19.95
**********authors5**********
{category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
**********authors6**********
{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}
**********authors7**********
{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}
**********authors8**********
{category=fiction, author=Evelyn Waugh, title=Sword of Honour, price=12.99}
**********authors9**********
{category=JavaWeb, author=X-rapido, title=Top-link, isbn=0-553-211231-3, price=32.68}
{category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}
**********authors10**********
{category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
{category=JavaWeb, author=X-rapido, title=Top-link, isbn=0-553-211231-3, price=32.68}
{category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}
**********authors11**********
{category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
{category=JavaWeb, author=X-rapido, title=Top-link, isbn=0-553-211231-3, price=32.68}
{category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}
**********authors12**********
{category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}
{category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
**********authors13**********
{category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}
{category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
**********authors14**********
{category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}
**********authors15**********
{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":"JavaWeb","author":"X-rapido","title":"Top-link","isbn":"0-553-211231-3","price":32.68},{"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}}
10
[{"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":"JavaWeb","author":"X-rapido","title":"Top-link","isbn":"0-553-211231-3","price":32.68},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}]
{color=red, price=19.95}
{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=JavaWeb, author=X-rapido, title=Top-link, isbn=0-553-211231-3, price=32.68}
{category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}
reference
Nigel Rees
Sayings of the Century
8.95
fiction
Evelyn Waugh
Sword of Honour
12.99
fiction
Herman Melville
Moby Dick
0-553-21311-3
8.99
JavaWeb
X-rapido
Top-link
0-553-211231-3
32.68
fiction
J. R. R. Tolkien
The Lord of the Rings
0-395-19395-8
22.99
red
19.95
**********authors16**********
5
Java2
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.ReadContext;
public class TestJsonPath3 {
public static void main(String[] args) {
String sjson = readtxt();
print("-----------------------getJsonValue0-----------------------");
getJsonValue0(sjson);
print("-----------------------getJsonValue1-----------------------");
getJsonValue1(sjson);
print("-----------------------getJsonValue2-----------------------");
getJsonValue2(sjson);
print("-----------------------getJsonValue3-----------------------");
getJsonValue3(sjson);
print("-----------------------getJsonValue4-----------------------");
getJsonValue4(sjson);
}
private static String readtxt() {
StringBuilder sb = new StringBuilder();
try {
FileReader fr = new FileReader("D:/books.txt");
BufferedReader bfd = new BufferedReader(fr);
String s = "";
while((s=bfd.readLine())!=null) {
sb.append(s);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(sb.toString());
return sb.toString();
}
/**
* 讀取json的一種寫法,得到匹配表達式的所有值
* */
private static void getJsonValue0(String json) {
List<String> authors = JsonPath.read(json, "$.store.book[*].author");
print(authors);
}
/**
* 讀取JSON得到某個具體值(推薦使用這種方法,一次解析多次調用)
* */
private static void getJsonValue1(String json) {
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");
print(author0);
print(author1);
}
/**
* 讀取json的一種寫法
* */
private static void getJsonValue2(String json) {
ReadContext ctx = JsonPath.parse(json);
// 獲取json中book數組中包含isbn的作者
List<String> authorsOfBooksWithISBN = ctx.read("$.store.book[?(@.isbn)].author");
// 獲取json中book數組中價格大於10的對象
List<Map<String, Object>> expensiveBooks = JsonPath
.using(Configuration.defaultConfiguration())
.parse(json)
.read("$.store.book[?(@.price > 10)]", List.class);
print(authorsOfBooksWithISBN);
print("********Map********");
printListMap(expensiveBooks);
}
/**
* 讀取JSON得到的值是一個String,所以不能用List存儲
* */
private static void getJsonValue3(String json) {
//Will throw an java.lang.ClassCastException
//List<String> list = JsonPath.parse(json).read("$.store.book[0].author");
//由於會拋異常,暫時註釋上面一行,要用的話,應使用下面的格式
String author = JsonPath.parse(json).read("$.store.book[0].author");
print(author);
}
/**
* 讀取json的一種寫法,支持邏輯表達式,&&和||
*/
private static void getJsonValue4(String json) {
List<Map<String, Object>> books1 = JsonPath.parse(json).read("$.store.book[?(@.price < 10 && @.category == 'fiction')]");
List<Map<String, Object>> books2 = JsonPath.parse(json).read("$.store.book[?(@.category == 'reference' || @.price > 10)]");
print("********books1********");
printListMap(books1);
print("********books2********");
printListMap(books2);
}
private static void print(List<String> list) {
for(Iterator<String> it = list.iterator();it.hasNext();) {
System.out.println(it.next());
}
}
private static void printListMap(List<Map<String, Object>> list) {
for(Iterator<Map<String, Object>> it = list.iterator();it.hasNext();) {
Map<String, Object> map = it.next();
for(Iterator iterator =map.entrySet().iterator();iterator.hasNext();) {
System.out.println(iterator.next());
}
}
}
private static void print(String s) {
System.out.println("\n"+s);
}
}
輸出
{"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":"JavaWeb","author":"X-rapido","title":"Top-link","isbn":"0-553-211231-3","price":32.68},{"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}},"expensive":10}
-----------------------getJsonValue0-----------------------
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/D:/workSpaces/SupportPackge/MavenRepository/org/apache/logging/log4j/log4j-slf4j-impl/2.0.2/log4j-slf4j-impl-2.0.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/D:/workSpaces/SupportPackge/MavenRepository/org/slf4j/slf4j-log4j12/1.7.10/slf4j-log4j12-1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory]
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
Nigel Rees
Evelyn Waugh
Herman Melville
X-rapido
J. R. R. Tolkien
-----------------------getJsonValue1-----------------------
Nigel Rees
Evelyn Waugh
-----------------------getJsonValue2-----------------------
Herman Melville
X-rapido
J. R. R. Tolkien
********Map********
category=fiction
author=Evelyn Waugh
title=Sword of Honour
price=12.99
category=JavaWeb
author=X-rapido
title=Top-link
isbn=0-553-211231-3
price=32.68
category=fiction
author=J. R. R. Tolkien
title=The Lord of the Rings
isbn=0-395-19395-8
price=22.99
-----------------------getJsonValue3-----------------------
Nigel Rees
-----------------------getJsonValue4-----------------------
********books1********
category=fiction
author=Herman Melville
title=Moby Dick
isbn=0-553-21311-3
price=8.99
********books2********
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=JavaWeb
author=X-rapido
title=Top-link
isbn=0-553-211231-3
price=32.68
category=fiction
author=J. R. R. Tolkien
title=The Lord of the Rings
isbn=0-395-19395-8
price=22.99
過濾器示例
Java
public static void main(String[] args) {
String json = readtxt();
Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);
// 過濾器鏈(查找包含isbn並category中有fiction或JavaWeb的值)
Filter filter = Filter.filter(Criteria.where("isbn").exists(true).and("category").in("fiction", "JavaWeb"));
List<Object> books = JsonPath.read(document, "$.store.book[?]", filter);
printOb(books);
System.out.println("\n----------------------------------------------\n");
// 自定義過濾器
Filter mapFilter = new Filter() {
@Override
public boolean apply(PredicateContext context) {
Map<String, Object> map = context.item(Map.class);
if (map.containsKey("isbn")) {
return true;
}
return false;
}
};
List<Object> books2 = JsonPath.read(document, "$.store.book[?]", mapFilter);
printOb(books2);
}
輸出
{category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
{category=JavaWeb, author=X-rapido, title=Top-link, isbn=0-553-211231-3, price=32.68}
{category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}
----------------------------------------------
{category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
{category=JavaWeb, author=X-rapido, title=Top-link, isbn=0-553-211231-3, price=32.68}
{category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}
由此可見,使用過濾器,或者使用上述的表達式,都是可以達到理想的效果。
示例中的books2中,注意到context.item(Map.class); 這句話。
這句中的Map.class是根據預定的結果類型定義的,如果返回的是String類型值,那就改爲String.class。
我的示例只簡單判斷了一下isbn屬性,可以根據實際情況進行變更條件。