json解析工具jsonpath

JsonPath提供的json解析非常强大,它提供了类似正则表达式的语法,基本上可以满足所有你想要获得的json内容。

引入

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
</dependency>

操作符

符号 描述
$ 要查询的根元素。 这将启动所有路径表达式。
@ 正在处理的当前节点。
* 通配符。 可在任何需要名称或数字的地方使用。
.. 深层扫描。 可在需要名称的任何地方使用。
.<name> 孩子节点
['<name>' (, '<name>')] 多个孩子
[<number> (, <number>)] 数组的下标(从0开始),可写多个。
[start:end] 数组的范围
[?(<expression>)] 过滤表达式。 表达式结果必须为布尔值。

函数

可以在路径的末尾调用函数-函数的输入是路径表达式的输出。 函数输出由函数本身决定。

函数 描述 输出类型
min() 计算数组中最小的元素 double
max() 计算数组中最大的元素 double
avg() 计算数组所有元素的平均值 double
stddev() 计算数组所有元素的标准差 double
length() 计算数组的长度 int
sum() 计算数组所有元素的和 double

过滤器

过滤器是用于过滤数组的逻辑表达式。 典型的过滤器为[?(@.age > 18)],其中@代表当前正在处理的节点。 可以使用逻辑运算符&&||创建更复杂的过滤器。 字符串文字必须用单引号或双引号引起来([?(@.color == 'blue')][?(@.color == "blue")])。

操作符 描述
== left is equal to right (note that 1 is not equal to '1')
!= left is not equal to right
< left is less than right
<= left is less or equal to right
> left is greater than right
>= left is greater than or equal to right
=~ 从左开始正则匹配字符串[?(@.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 左边(数组或字符串)应为空

例子

{
    "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 The authors of all books ["Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"]
$..author All authors ["Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"]
$.store.* All things, both books and bicycles
$.store..price The price of everything [8.95,12.99, 8.99, 22.99,19.95]
$..book[2] The third book
$.book[-2] The second to last book
$..book[0,1] The first two books
$..book[:2] All books from index 0 (inclusive) until index 2 (exclusive)
$..book[1:2] All books from index 1 (inclusive) until index 2 (exclusive)
$..book[-2:] Last two books
$..book[2:] Book number two from tail
$..book[?(@.isbn)] All books with an ISBN number
$.store.book[?(@.price < 10)] All books in store cheaper than 10
$..book[?(@.author =~ /*.REES/i)] All books matching regex (ignore case)
$..* Give me every thing
$..book.length() The number of books [4]

api

#方式1
String json = "...";
List<String> authors = JsonPath.read(json, "$.store.book[*].author");
#方式2:只需读取一次json
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");
#方式3
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);

返回类型

不确定路径始终返回一个列表,如果路径包含以下内容,则该路径是不确定的:

  • ..: 深度扫描
  • ?(<expression>): 表达式
  • [<number>, <number> (, <number>)]:数组多索引
#类型转换 MappingProvider SPI提供了一个简单的对象映射器
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);

设置值

String newJson = JsonPath.parse(json).set("$['store']['book'][0]['author']", "Paul").jsonString();

配置

#json
[
   {
      "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']");
#DEFAULT_PATH_LEAF_TO_NULL : 此选项使JsonPath对于缺少的叶子返回null。
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']");
#ALWAYS_RETURN_LIST: 即使路径是确定的,此选项也将JsonPath配置为返回类型为列表。
Configuration conf = Configuration.defaultConfiguration();
//ClassCastException thrown
List<String> genders0 = JsonPath.using(conf).parse(json).read("$[0]['gender']");
Configuration conf2 = conf.addOptions(Option.ALWAYS_RETURN_LIST);
//Works fine
List<String> genders0 = JsonPath.using(conf2).parse(json).read("$[0]['gender']");
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。