1
2
3
4
5
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
</dependency>
JsonPath 表达式可以用 . 或者 [] 表示。
- $.store.book[0].title
- $['store']['book'][0]['title']
符号
| 符号 | 描述 | 
|---|---|
| $ | 根节点对象 | 
| @ | 过滤器处理的当前节点对象 | 
| * | 通配符,可以表示一个名字或数字 | 
| .. | 全局匹配 | 
| .<name> | .表示的子节点 | 
| ['<name>' (, '<name>')] | []表示的子节点 | 
| [<number> (, <number>)] | 数组索引 | 
| [start:end] | 数组切片 | 
| [?(<expression>)] | 过滤器表达式,表达式结果必须是boolean | 
函数
| 函数 | 描述 | 输出 | 
|---|---|---|
| min() | 数组里的最小值 | Double | 
| max() | 数组里的最大值 | Double | 
| avg() | 数组平均值 | Double | 
| stddev() | 数组标准差 | Double | 
| length() | 数组长度 | Integer | 
过滤器
| 操作 | 描述 | 
|---|---|
| == | 等于 | 
| != | 不等 | 
| < | 小于 | 
| <= | 小于等于 | 
| > | 大于 | 
| >= | 大于等于 | 
| =~ | 正则表达式,例如 [?(@.name =~ /foo.*?/i)] | 
| in | 包含, 例如 [?(@.size in [‘S’, ‘M’])] | 
| nin | 不包含 | 
| subsetof | 子集,例如 [?(@.sizes subsetof [‘S’, ‘M’, ‘L’])] | 
| anyof | 有交集,例如 [?(@.sizes anyof [‘M’, ‘L’])] | 
| noneof | 无交集,例如 [?(@.sizes noneof [‘M’, ‘L’])] | 
| size | 数组、字符串长度相等 | 
| empty | 数组、字符串为空 | 
示例
给定Json:
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
{
    "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 表达式及结果:
| JsonPath表达式 | 结果(点链接查看在线结果) | 
|---|---|
| $.store.book[*].author | 全部书的作者 | 
| $..author | 全部作者 | 
| $.store.* | 全部东西 | 
| $.store..price | 全部价格 | 
| $..book[2] | 第3本 | 
| $..book[-2] | 倒数第2本 | 
| $..book[0,1] | 前2本 | 
| $..book[:2] | 前2本 | 
| $..book[1:2] | 第2本 | 
| $..book[-2:] | 最后2本 | 
| $..book[2:] | 第3本到最后 | 
| $..book[?(@.isbn)] | 有 ISBN 的全部书 | 
| $.store.book[?(@.price < 10)] | 价格小于 10 的全部书 | 
| $..book[?(@.price <= $[‘expensive’])] | 价格小于 expensive 的全部书 | 
| $..book[?(@.author =~ /.*REES/i)] | [作者符合正则表达式 /.REES/i 的全部书](https://jsonpath.herokuapp.com/?path=$..book[?(@.author =~ /.REES/i)]) | 
| $..* | 全部 | 
| $..book.length() | 书的数量 | 
用法
- 单次读取 - 1 2 3 - String json = "..."; List<String> authors = JsonPath.read(json, "$.store.book[*].author"); 
- 多次读取:先解析 Json 为 ReadContext,再通过 ReadContext 读取,以避免多次解析 Json。 - 1 2 3 4 5 - String json = "..."; ReadContext ctx = JsonPath.parse(json); List<String> authorsOfBooksWithISBN = ctx.read("$.store.book[?(@.isbn)].author"); 
返回值
- JsonPath 表达式不明确时,返回值为 list 。不明确的表达式包含: - ..:全局匹配
- ?(<expression>):过滤器表达式
- [<number>, <number> (, <number>)]:多索引
 
- JsonPath 表达式明确时,返回值为 POJO。 - 1 2 3 4 - Configuration conf = Configuration.builder() .jsonProvider(new GsonJsonProvider()) .build(); Book book = JsonPath.using(conf).parse(json).read("$.store.book[0]", Book.class); 
- 泛型 - 1 2 3 - TypeRef<List<String>> typeRef = new TypeRef<List<String>>() {}; List<String> titles = JsonPath.parse(JSON_DOCUMENT).read("$.store.book[*].title", typeRef); 
配置
Configuration.builder() 实现对 JsonPath 配置。
1
2
3
Configuration conf = Configuration.builder()
                                  .options(Option.ALWAYS_RETURN_LIST)
                                  .build();
共5个配置选项:
- Option.DEFAULT_PATH_LEAF_TO_NULL:配置后空节点返回 null。 - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 - * [ * { * "foo" : "foo1", * "bar" : "bar1" * } * { * "foo" : "foo2" * } * ] *</pre> * * the path : * * "$[*].bar" * * Without flag ["bar1"] is returned * With flag ["bar1", null] is returned 
- Option.ALWAYS_RETURN_LIST:配置后返回值为 list,不返回 POJO。 
- Option.AS_PATH_LIST:配置后返回值为路径,非对象。 - 1 2 3 4 5 6 7 8 9 10 - 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']"); 
- Option.SUPPRESS_EXCEPTIONS:配置后异常被抑制。如果同时配置了 ALWAYS_RETURN_LIST ,发生异常时返回 empty list,否则返回 null。 
- Option.REQUIRE_PROPERTIES:禁止通配符。比如 $[*].b,会抛出 PathNotFoundException 异常。 
