一款好用的json解析工具,JsonPath。
1. 介紹
包: com.jayway.jsonpath.JsonPath;
pom: <dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
</dependency>
類似於XPath在xml文件中的定位,JsonPath表示式通常是用來路徑檢索或設定Json的。其表示式可以接受“dot–notation”和“bracket–notation”格式,例如$.store.book[0].title、$[‘store’][‘book’][0][‘title’]
2. 操作符
符號 | 描述 |
---|---|
$ | 查詢的根節點物件,用於表示一個json資料,可以是陣列或物件 |
@ | 過濾器斷言(filter predicate)處理的當前節點物件,類似於java中的this欄位 |
* | 萬用字元,可以表示一個名字或數字 |
.. | 可以理解為遞迴搜尋,Deep scan. Available anywhere a name is required. |
.<name> | 表示一個子節點 |
[‘<name>’ (, ‘<name>’)] | 表示一個或多個子節點 |
[<number> (, <number>)] | 表示一個或多個數組下標 |
[start:end] | 陣列片段,區間為[start,end),不包含end |
[?(<expression>)] | 過濾器表示式,表示式結果必須是boolean |
3. 函式
可以在JsonPath表示式執行後進行呼叫,其輸入值為表示式的結果。
名稱 | 描述 | 輸出 |
---|---|---|
min() | 獲取數值型別陣列的最小值 | Double |
max() | 獲取數值型別陣列的最大值 | Double |
avg() | 獲取數值型別陣列的平均值 | Double |
stddev() | 獲取數值型別陣列的標準差 | Double |
length() | 獲取數值型別陣列的長度 | Integer |
4. 過濾器
過濾器是用於過濾陣列的邏輯表示式,一個通常的表示式形如:[?(@.age > 18)],可以通過邏輯表示式&&或||組合多個過濾器表示式,例如[?(@.price < 10 && @.category == ‘fiction’)],字串必須用單引號或雙引號包圍,例如[?(@.color == ‘blue’)] or [?(@.color == “blue”)]。
操作符 | 描述 |
---|---|
== | 等於符號,但數字1不等於字元1(note that 1 is not equal to ‘1’) |
!= | 不等於符號 |
< | 小於符號 |
<= | 小於等於符號 |
> | 大於符號 |
>= | 大於等於符號 |
=~ | 判斷是否符合正則表示式,例如[?(@.name =~ /foo.*?/i)] |
in | 所屬符號,例如[?(@.size in [‘S’, ‘M’])] |
nin | 排除符號 |
size | size of left (array or string) should match right |
empty | 判空符號 |
5. 示例
{
"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 或 $..author |
[ “Nigel Rees”, “Evelyn Waugh”, “Herman Melville”, “J. R. R. Tolkien” ] |
$.store.* 顯示所有葉子節點值 | [ [ { ”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 } ], { ”color” : “red”, ”price” : 19.95 } ] |
$.store..price | [ 8.95, 12.99, 8.99, 22.99, 19.95 ] |
$..book[0,1] 或 $..book[:2] |
[ { ”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 } ] |
$..book[-2:] | 獲取最後兩本書 |
$..book[2:] | [ { ”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 } ] |
$..book[?(@.isbn)] | 所有具有isbn屬性的書 |
$.store.book[?(@.price < 10)] | 所有價格小於10的書 |
$..book[?(@.price <= $[‘expensive’])] | 所有價格低於expensive欄位的書 |
$..book[?(@.author =~ /.*REES/i)] | 所有符合正則表示式的書 [ { ”category” : “reference”, ”author” : “Nigel Rees”, ”title” : “Sayings of the Century”, ”price” : 8.95 } ] |
$..* | 返回所有 |
$..book.length() | [ 4 ] |
6. 常見用法
通常是直接使用靜態方法API進行呼叫,例如:
String json = "...";
List<String> authors = JsonPath.read(json, "$.store.book[*].author");
但以上方式僅僅適用於解析一次json的情況,如果需要對同一個json解析多次,不建議使用,因為每次read都會重新解析一次json,針對此種情況,建議使用ReadContext、WriteContext,例如:
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);
7. 返回值是什麼?
通常read後的返回值會進行自動轉型到指定的型別,對應明確定義definite的表示式,應指定其對應的型別,對於indefinite含糊表示式,例如包括..、?(<expression>)、[<number>, <number> (, <number>)],通常應該使用陣列。如果需要轉換成具體的型別,則需要通過configuration配置mappingprovider,如下:
String json = "{\"date_as_long\" : 1411455611975}";
//使用JsonSmartMappingProvider
Date date = JsonPath.parse(json).read("$['date_as_long']", Date.class);
//使用GsonMappingProvider
Book book = JsonPath.parse(json).read("$.store.book[0]", Book.class);
8. MappingProvider SPI反序列化器
其中JsonSmartMappingProvider提供瞭如下基本資料型別的轉換,此provider是預設設定的,在Configuration.defaultConfiguration()中返回的DefaultsImpl類,使用的就是JsonSmartMappingProvider。
DEFAULT.registerReader(Long.class, new LongReader());
DEFAULT.registerReader(long.class, new LongReader());
DEFAULT.registerReader(Integer.class, new IntegerReader());
DEFAULT.registerReader(int.class, new IntegerReader());
DEFAULT.registerReader(Double.class, new DoubleReader());
DEFAULT.registerReader(double.class, new DoubleReader());
DEFAULT.registerReader(Float.class, new FloatReader());
DEFAULT.registerReader(float.class, new FloatReader());
DEFAULT.registerReader(BigDecimal.class, new BigDecimalReader());
DEFAULT.registerReader(String.class, new StringReader());
DEFAULT.registerReader(Date.class, new DateReader());
切換Provider,如下:
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);
}
});
9. Predicates過濾器斷言
有三種方式建立過濾器斷言。
9.1 Inline Predicates
即使用過濾器斷言表示式?(<@expression>),例如:
List<Map<String, Object>> books = JsonPath.parse(json)
.read("$.store.book[?(@.price < 10)]");
9.2 Filter Predicates
使用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);
Filter fooOrBar = filter(
where("foo").exists(true)).or(where("bar").exists(true)
);
Filter fooAndBar = filter(
where("foo").exists(true)).and(where("bar").exists(true)
);
注意:
- JsonPath表示式中必須要有斷言佔位符?,當有多個佔位符時,會依據順序進行替換。
- 多個filter之間還可以使用or或and。
9.3 Roll Your Own
自己實現Predicate介面。
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);
10. 返回檢索到的Path路徑列表
有時候需要返回當前JsonPath表示式所檢索到的全部路徑,可以如下使用:
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']");
11. 配置Options
11.1 DEFAULT_PATH_LEAF_TO_NULL
當檢索不到時返回null物件,否則如果不配置這個,會直接丟擲異常PathNotFoundException,例如:
[
{
"name" : "john",
"gender" : "male"
},
{
"name" : "ben"
}
]
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 gender0 = JsonPath.using(conf2).parse(json).read("$[0]['gender']");
//Works fine (null is returned)
String gender1 = JsonPath.using(conf2).parse(json).read("$[1]['gender']");
11.2 ALWAYS_RETURN_LIST
總是返回list,即便是一個確定的非list型別,也會被包裝成list。
11.3 SUPPRESS_EXCEPTIONS
不丟擲異常,需要判斷如下:
- ALWAYS_RETURN_LIST開啟,則返回空list
- ALWAYS_RETURN_LIST關閉,則返回null
11.4 AS_PATH_LIST
返回path
11.5 REQUIRE_PROPERTIES
如果設定,則不允許使用萬用字元,比如$[*].b,會丟擲PathNotFoundException異常。
12. Cache SPI
每次read時都會獲取cache,以提高速度,但預設情況下是不啟用的。
@Override
public <T> T read(String path, Predicate... filters) {
notEmpty(path, "path can not be null or empty");
Cache cache = CacheProvider.getCache();
path = path.trim();
LinkedList filterStack = new LinkedList<Predicate>(asList(filters));
String cacheKey = Utils.concat(path, filterStack.toString());
JsonPath jsonPath = cache.get(cacheKey);
if(jsonPath != null){
return read(jsonPath);
} else {
jsonPath = compile(path, filters);
cache.put(cacheKey, jsonPath);
return read(jsonPath);
}
}
JsonPath 2.1.0提供新的spi,必須在使用前或丟擲JsonPathException前配置。目前提供了兩種實現:
- com.jayway.jsonpath.spi.cache.NOOPCache (no cache)
- com.jayway.jsonpath.spi.cache.LRUCache (default, thread safe)
如果想要自己實現,例如:
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);
}
});
參考: