JsonPath提供的json解析非常强大,非常方便的获取json的内容.
需要的jar网上有!
语法简介
JsonPath | 描述 |
$ | 根节点 |
@ | 当前节点 |
.or[] | 子节点 |
.. | 选择所有符合条件的节点 |
* | 所有节点 |
[] | 迭代器标示,如数组下标 |
[,] | 支持迭代器中做多选 |
[start:end:step] | 数组切片运算符 |
?() | 支持过滤操作 |
() | 支持表达式计算 |
代码实例:
1 { "store": { 2 "book": [ 3 { "category": "reference", 4 "author": "Nigel Rees", 5 "title": "Sayings of the Century", 6 "price": 8.95 7 }, 8 { "category": "fiction", 9 "author": "Evelyn Waugh", 10 "title": "Sword of Honour", 11 "price": 12.99, 12 "isbn": "0-553-21311-3" 13 } 14 ], 15 "bicycle": { 16 "color": "red", 17 "price": 19.95 18 } 19 } 20 }
解析代码:
1 //输出book[0]的author值 2 String author = JsonPath.read(json, "$.store.book[0].author"); 3 System.out.println("author\t"+author); 4 //输出全部author的值,使用Iterator迭代 5 List<String> authors = JsonPath.read(json, "$.store.book[*].author"); 6 System.out.println("authors\t"+authors); 7 8 //输出book[*]中category == 'reference'的book 9 List<Object> books = JsonPath.read(json, "$.store.book[?(@.category == 'reference')]"); 10 System.out.println("books\t"+books); 11 //输出book[*]中category == 'reference'的book或者 12 List<Object> books2 = JsonPath.read(json, "$.store.book[?(@.category == 'reference' || @.price>10)]"); 13 System.out.println("books2\t"+books2); 14 15 //输出book[*]中category == 'reference'的book的author 16 List<Object> books1 = JsonPath.read(json, "$.store.book[?(@.category == 'reference')].author"); 17 System.out.println("books1\t"+books1); 18 19 //输出book[*]中price>10的book 20 List<Object> b1 = JsonPath.read(json, "$.store.book[?(@.price>10)]"); 21 System.out.println("b1"+b1); 22 23 //输出book[*]中含有isbn元素的book 24 List<Object> b2 = JsonPath.read(json, "$.store.book[?(@.isbn)]"); 25 System.out.println("b2"+b2); 26 27 //输出该json中所有price的值 28 List<Double> prices = JsonPath.read(json, "$..price"); 29 System.out.println("prices"+prices); 30 31 //输出该json中所有title的值 32 List<Double> title = JsonPath.read(json, "$..title"); 33 System.out.println("title"+title); 34 //输出该json中book 0,1的值 35 List<Double> book01 = JsonPath.read(json, "$..book[0,1]"); 36 System.out.println("book01"+book01); 37 /* //输出该json中book 0,1的值 38 List<Double> book012 = JsonPath.read(json, "$..book[-2:]"); 39 System.out.println("book012"+book012);*/ 40 41 //可以提前编辑一个路径,并多次使用它 42 JsonPath path = JsonPath.compile("$.store.book[*]"); 43 List<Object> b3 = path.read(json); 44 System.out.println("path\t"+path+"\n"+b3);
JsonPath 解析比较简单,使用几次后就会熟练!
来源:https://www.cnblogs.com/fyqx/p/6832473.html