使用jsonpath解析json内容
JsonPath提供的json解析非常强大,它提供了类似正则表达式的语法,基本上可以满足所有你想要获得的json内容。下面我把官网介绍的每个表达式用代码实现,可以更直观的知道该怎么用它。
一.首先需要依赖的jar包
二.因为编译的时候会报log4j的警报,所以需要在项目的src目录下新建log4j.properties文件,内容如下:
log4j.rootLogger=WARN, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
三.准备一个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": "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
}
四.我们从代码中分析用法,代码如下
package com.jsonpath; import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Iterator;
import java.util.List;
import java.util.Map; import net.minidev.json.JSONArray; import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.ReadContext; /**
* @author QiaoJiafei
* @version 创建时间:2016年3月2日 下午3:37:42
* 类说明
*/
public class TestJsonPath { public static void main(String[] args) {
// TODO Auto-generated method stub
String sjson = readtxt();
//String sjson = "{\"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}";
/*
print("--------------------------------------getJsonValue0--------------------------------------");
getJsonValue0(sjson);
print("--------------------------------------getJsonValue1--------------------------------------");
getJsonValue1(sjson);
print("--------------------------------------getJsonValue2--------------------------------------");
getJsonValue2(sjson);
print("--------------------------------------getJsonValue3--------------------------------------");
getJsonValue3(sjson);
print("--------------------------------------getJsonValue4--------------------------------------");
getJsonValue4(sjson);
*/ print("--------------------------------------getJsonValue--------------------------------------");
getJsonValue(sjson);
} private static String readtxt() {
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
try {
FileReader fr = new FileReader("D:/workspace/PressureTest/json.txt");
BufferedReader bfd = new BufferedReader(fr);
String s = "";
while((s=bfd.readLine())!=null) {
sb.append(s);
}
} catch (Exception e) {
// TODO Auto-generated catch block
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); } /**
* 读取json的一种写法,得到匹配表达式的所有值
* */
private static void getJsonValue0(String json) {
// TODO Auto-generated method stub
List<String> authors = JsonPath.read(json, "$.store.book[*].author");
//System.out.println(authors.size());
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); List<String> authorsOfBooksWithISBN = ctx.read("$.store.book[?(@.isbn)].author"); 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");
//由于会抛异常,暂时注释上面一行,要用的话,应使用下面的格式 //Works fine
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(books1);
} 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();) {
print("****");
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();
print("****");
for(Iterator iterator =map.entrySet().iterator();iterator.hasNext();) {
System.out.println(iterator.next());
} }
} private static void print(String s) {
System.out.println(s);
} }
1.首先我们看getJsonValue()这个方法的输出结果:
--------------------------------------getJsonValue--------------------------------------
**************authors1**************
Nigel Rees
Evelyn Waugh
Herman Melville
J. R. R. Tolkien
**************authors2**************
Nigel Rees
Evelyn Waugh
Herman Melville
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":"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
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=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}
**************authors10**************
{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}
**************authors11**************
{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}
**************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":"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":"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=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
fiction
J. R. R. Tolkien
The Lord of the Rings
0-395-19395-8
22.99
red
19.95
**************authors16**************
4
2.然后看getJsonValue0()、getJsonValue1()、getJsonValue2()、getJsonValue3()、getJsonValue4()的输出结果
--------------------------------------getJsonValue0--------------------------------------
Nigel Rees
Evelyn Waugh
Herman Melville
J. R. R. Tolkien
--------------------------------------getJsonValue1--------------------------------------
Nigel Rees
Evelyn Waugh
--------------------------------------getJsonValue2--------------------------------------
Herman Melville
J. R. R. Tolkien
****************Map****************
****
category=fiction
author=Evelyn Waugh
title=Sword of Honour
price=12.99
****
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=fiction
author=Herman Melville
title=Moby Dick
isbn=0-553-21311-3
price=8.99
3.相应的解释已经在代码中注释,更多的用法详见官网链接:https://github.com/jayway/JsonPath
4.如果只是想简单的处理json,也可以使用JSONObject和JSONArray,具体用法详见我的这篇文章:http://www.cnblogs.com/qiaoyeye/p/4730930.html
----------更新2016年08月19日10:06:09-------
You can use &&
and ||
to combine multiple predicates [?(@.price < 10 && @.category == 'fiction')]
, [?(@.category == 'reference' || @.price > 10)]
这个好厉害,可以这样用
JsonPath.read(json, "$..farePrices[?(@.priceType == 'SalePrice' && @.passengerType == 'ADULT')].amount");
使用jsonpath解析json内容的更多相关文章
- JSONPath解析json
JSONPath - 用于JSON的XPath 用来解析多层嵌套的json数据;JsonPath 是一种信息抽取类库,是从JSON文档中抽取指定信息的工具. 考虑到接下来计划开发一个自动化测试平台,在 ...
- 使用json-path解析json
在我们的日常开发中,有时候需要从一个json字符串中获取一个值,或者从一段json字符串中获取到某些值,如果先使用Gson或Jackson转换成java对象在获取值,有些时候是很麻烦的,那么有没有一种 ...
- json-path解析json方便可靠
JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document. JsonPat ...
- 安卓解析json,使用BaseAdapter添加至ListView中,中间存储用JavaBean来实现
这是一个小练习,要求解析一个提供的json文件.并将其中的id,title值获取,以ListView形式展示出来.(开发工具是android studio) 下面开始: 首先我想到的是先把json文件 ...
- Python | JSON 数据解析(Json & JsonPath)
一.什么是JSON? JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式.它基于 ECMAScript (欧洲计算机协会制定的js规范)的一 ...
- Kettle解析JSON错误,We MUST have the same number of values for all paths,We can not find and data with path [$.
最近公司要从聚石塔上抽取数据,其中有JSON格式数据,所以学习一下Kettle解析JSON,碰到小小问题,记录一下: (1) 2015/07/15 15:22:48 - trade_detail.0 ...
- 使用Newtonsoft.Json.dll(JSON.NET)动态解析JSON、.net 的json的序列化与反序列化(一)
在开发中,我非常喜欢动态语言和匿名对象带来的方便,JSON.NET具有动态序列化和反序列化任意JSON内容的能力,不必将它映射到具体的强类型对象,它可以处理不确定的类型(集合.字典.动态对象和匿名对象 ...
- 阶段一:通过网络请求,获得并解析JSON数据(天气应用)
“阶段一”是指我第一次系统地学习Android开发.这主要是对我的学习过程作个记录. 在上一篇阶段一:解析JSON中提到,最近在写一个很简单的天气预报应用.即使功能很简单,但我还是想把它做成一个相对完 ...
- C语言创建及解析Json的使用法则
参考原文:http://blog.csdn.net/xukai871105/article/details/33013455 JSON(JavaScriptObject Notation)是一种轻量级 ...
随机推荐
- 晒自己做的一个管理系统(清新风格)EasyUI
最近项目结束了,现在也要自己总结一下自己的成果了,总结会加深自己对项目的印象的.这里我就先晒一些作品图片了,希望大家看了会赞美一个! 项目虽然结束了,但是接下来的这个项目可就不是我一个人可以搞定的了, ...
- kFreeBsd 国内开源镜像站汇总
从http://bbs.chinaunix.net/archiver/tid-3756178.html这里抽取了debian源中支撑kfreebsd架构的源. 中科大: http://debian.u ...
- 最小生成树Kruskal算法(邻接矩阵和邻接表)
最小生成树,克鲁斯卡尔算法. 算法简述: 将每个顶点看成一个图. 在所有图中找权值最小的边.将这条边的两个图连成一个图, 重复上一步.直到只剩一个图. 注:将abcdef每个顶点看成一个图.将最小权值 ...
- php多版本管理phpenv
曾经有试过phpbrew的童鞋应该知道有多复杂 虽然这个好久没更新了,还是可以用的-- github:phpenv/phpenv 它的原理就是处理PATH变量,将你要求的php版本的路径加到PATH的 ...
- ahjesus不断完善的js小"内裤"
String.prototype.isNullOrWhiteSpace = function () { /// <summary> /// 变量是undefined或者null或者空字符串 ...
- velocity merge作为工具类从web上下文和jar加载模板的两种常见情形
很多时候,处于各种便利性或折衷或者通用性亦或是限制的原因,会借助于模板生成结果,在此介绍两种使用velocity merge的情形,第一种是和spring mvc一样,将模板放在velocityCon ...
- CentOS6.5 安装Zookeeper集群
1.下载解压 2.配置环境变量:vi ~/.bashrc 或者 vi /etc/profile [hadoopuser@Linux01 ~]$ vi ~/.bashrc # zookeeper ...
- MAC下 JDK环境配置、版本切换以及ADB环境配置
网上方法,自己总结:亲测可行! 一.JDK环境配置.版本切换: 通过命令’jdk6′, ‘jdk7′,’jdk8’轻松切换到对应的Java版本: 1.首先安装所有的JDk:* Mac自带了的JDK6, ...
- WebForm(ASP开发方式,IIS服务器、WebForm开发基础)
一.B/S和C/S 1.C/S C/S 架构是一种典型的两层架构,其全程是Client/Server,即客户端服务器端架构,其客户端包含一个或多个在用户的电脑上运行的程序,而服务器端有两种,一种是数据 ...
- 【GOF23设计模式】模板方法模式
来源:http://www.bjsxt.com/ 一.[GOF23设计模式]_模板方法模式.钩子函数.方法回调.好莱坞原则 package com.test.templateMethod; publi ...