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文本

  1. {
  2. "store": {
  3. "book": [
  4. {
  5. "category": "reference",
  6. "author": "Nigel Rees",
  7. "title": "Sayings of the Century",
  8. "price": 8.95
  9. },
  10. {
  11. "category": "fiction",
  12. "author": "Evelyn Waugh",
  13. "title": "Sword of Honour",
  14. "price": 12.99
  15. },
  16. {
  17. "category": "fiction",
  18. "author": "Herman Melville",
  19. "title": "Moby Dick",
  20. "isbn": "0-553-21311-3",
  21. "price": 8.99
  22. },
  23. {
  24. "category": "fiction",
  25. "author": "J. R. R. Tolkien",
  26. "title": "The Lord of the Rings",
  27. "isbn": "0-395-19395-8",
  28. "price": 22.99
  29. }
  30. ],
  31. "bicycle": {
  32. "color": "red",
  33. "price": 19.95
  34. }
  35. },
  36. "expensive": 10
  37. }

四.我们从代码中分析用法,代码如下

  1. package com.jsonpath;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileReader;
  6. import java.util.Iterator;
  7. import java.util.List;
  8. import java.util.Map;
  9.  
  10. import net.minidev.json.JSONArray;
  11.  
  12. import com.jayway.jsonpath.Configuration;
  13. import com.jayway.jsonpath.JsonPath;
  14. import com.jayway.jsonpath.ReadContext;
  15.  
  16. /**
  17. * @author QiaoJiafei
  18. * @version 创建时间:2016年3月2日 下午3:37:42
  19. * 类说明
  20. */
  21. public class TestJsonPath {
  22.  
  23. public static void main(String[] args) {
  24. // TODO Auto-generated method stub
  25. String sjson = readtxt();
  26. //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}";
  27. /*
  28. print("--------------------------------------getJsonValue0--------------------------------------");
  29. getJsonValue0(sjson);
  30. print("--------------------------------------getJsonValue1--------------------------------------");
  31. getJsonValue1(sjson);
  32. print("--------------------------------------getJsonValue2--------------------------------------");
  33. getJsonValue2(sjson);
  34. print("--------------------------------------getJsonValue3--------------------------------------");
  35. getJsonValue3(sjson);
  36. print("--------------------------------------getJsonValue4--------------------------------------");
  37. getJsonValue4(sjson);
  38. */
  39.  
  40. print("--------------------------------------getJsonValue--------------------------------------");
  41. getJsonValue(sjson);
  42. }
  43.  
  44. private static String readtxt() {
  45. // TODO Auto-generated method stub
  46. StringBuilder sb = new StringBuilder();
  47. try {
  48. FileReader fr = new FileReader("D:/workspace/PressureTest/json.txt");
  49. BufferedReader bfd = new BufferedReader(fr);
  50. String s = "";
  51. while((s=bfd.readLine())!=null) {
  52. sb.append(s);
  53. }
  54. } catch (Exception e) {
  55. // TODO Auto-generated catch block
  56. e.printStackTrace();
  57. }
  58. System.out.println(sb.toString());
  59. return sb.toString();
  60. }
  61.  
  62. private static void getJsonValue(String json) {
  63. //The authors of all books:获取json中store下book下的所有author值
  64. List<String> authors1 = JsonPath.read(json, "$.store.book[*].author");
  65.  
  66. //All authors:获取所有json中所有author的值
  67. List<String> authors2 = JsonPath.read(json, "$..author");
  68.  
  69. //All things, both books and bicycles //authors3返回的是net.minidev.json.JSONArray:获取json中store下的所有value值,不包含key,如key有两个,book和bicycle
  70. List<Object> authors3 = JsonPath.read(json, "$.store.*");
  71.  
  72. //The price of everything:获取json中store下所有price的值
  73. List<Object> authors4 = JsonPath.read(json, "$.store..price");
  74.  
  75. //The third book:获取json中book数组的第3个值
  76. List<Object> authors5 = JsonPath.read(json, "$..book[2]");
  77.  
  78. //The first two books:获取json中book数组的第1和第2两个个值
  79. List<Object> authors6 = JsonPath.read(json, "$..book[0,1]");
  80.  
  81. //All books from index 0 (inclusive) until index 2 (exclusive):获取json中book数组的前两个区间值
  82. List<Object> authors7 = JsonPath.read(json, "$..book[:2]");
  83.  
  84. //All books from index 1 (inclusive) until index 2 (exclusive):获取json中book数组的第2个值
  85. List<Object> authors8 = JsonPath.read(json, "$..book[1:2]");
  86.  
  87. //Last two books:获取json中book数组的最后两个值
  88. List<Object> authors9 = JsonPath.read(json, "$..book[-2:]");
  89.  
  90. //Book number two from tail:获取json中book数组的第3个到最后一个的区间值
  91. List<Object> authors10 = JsonPath.read(json, "$..book[2:]");
  92.  
  93. //All books with an ISBN number:获取json中book数组中包含isbn的所有值
  94. List<Object> authors11 = JsonPath.read(json, "$..book[?(@.isbn)]");
  95.  
  96. //All books in store cheaper than 10:获取json中book数组中price<10的所有值
  97. List<Object> authors12 = JsonPath.read(json, "$.store.book[?(@.price < 10)]");
  98.  
  99. //All books in store that are not "expensive":获取json中book数组中price<=expensive的所有值
  100. List<Object> authors13 = JsonPath.read(json, "$..book[?(@.price <= $['expensive'])]");
  101.  
  102. //All books matching regex (ignore case):获取json中book数组中的作者以REES结尾的所有值(REES不区分大小写)
  103. List<Object> authors14 = JsonPath.read(json, "$..book[?(@.author =~ /.*REES/i)]");
  104.  
  105. //Give me every thing:逐层列出json中的所有值,层级由外到内
  106. List<Object> authors15 = JsonPath.read(json, "$..*");
  107.  
  108. //The number of books:获取json中book数组的长度
  109. List<Object> authors16 = JsonPath.read(json, "$..book.length()");
  110. print("**************authors1**************");
  111. print(authors1);
  112. print("**************authors2**************");
  113. print(authors2);
  114. print("**************authors3**************");
  115. printOb(authors3);
  116. print("**************authors4**************");
  117. printOb(authors4);
  118. print("**************authors5**************");
  119. printOb(authors5);
  120. print("**************authors6**************");
  121. printOb(authors6);
  122. print("**************authors7**************");
  123. printOb(authors7);
  124. print("**************authors8**************");
  125. printOb(authors8);
  126. print("**************authors9**************");
  127. printOb(authors9);
  128. print("**************authors10**************");
  129. printOb(authors10);
  130. print("**************authors11**************");
  131. printOb(authors11);
  132. print("**************authors12**************");
  133. printOb(authors12);
  134. print("**************authors13**************");
  135. printOb(authors13);
  136. print("**************authors14**************");
  137. printOb(authors14);
  138. print("**************authors15**************");
  139. printOb(authors15);
  140. print("**************authors16**************");
  141. printOb(authors16);
  142.  
  143. }
  144.  
  145. /**
  146. * 读取json的一种写法,得到匹配表达式的所有值
  147. * */
  148. private static void getJsonValue0(String json) {
  149. // TODO Auto-generated method stub
  150. List<String> authors = JsonPath.read(json, "$.store.book[*].author");
  151. //System.out.println(authors.size());
  152. print(authors);
  153.  
  154. }
  155.  
  156. /**
  157. * 读取json的一种写法,得到某个具体值
  158. * */
  159. private static void getJsonValue1(String json) {
  160. Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);
  161.  
  162. String author0 = JsonPath.read(document, "$.store.book[0].author");
  163. String author1 = JsonPath.read(document, "$.store.book[1].author");
  164. print(author0);
  165. print(author1);
  166.  
  167. }
  168.  
  169. /**
  170. * 读取json的一种写法
  171. * */
  172. private static void getJsonValue2(String json) {
  173. ReadContext ctx = JsonPath.parse(json);
  174.  
  175. List<String> authorsOfBooksWithISBN = ctx.read("$.store.book[?(@.isbn)].author");
  176.  
  177. List<Map<String, Object>> expensiveBooks = JsonPath
  178. .using(Configuration.defaultConfiguration())
  179. .parse(json)
  180. .read("$.store.book[?(@.price > 10)]", List.class);
  181. print(authorsOfBooksWithISBN);
  182. print("****************Map****************");
  183. printListMap(expensiveBooks);
  184. }
  185.  
  186. /**
  187. *读取json的一种写法
  188. *得到的值是一个String,所以不能用List存储
  189. * */
  190. private static void getJsonValue3(String json) {
  191. //Will throw an java.lang.ClassCastException
  192. //List<String> list = JsonPath.parse(json).read("$.store.book[0].author");
  193. //由于会抛异常,暂时注释上面一行,要用的话,应使用下面的格式
  194.  
  195. //Works fine
  196. String author = JsonPath.parse(json).read("$.store.book[0].author");
  197. print(author);
  198. }
  199.  
  200. /**
  201. *读取json的一种写法
  202. *支持逻辑表达式,&&和||
  203. * */
  204. private static void getJsonValue4(String json) {
  205. List<Map<String, Object>> books1 = JsonPath.parse(json)
  206. .read("$.store.book[?(@.price < 10 && @.category == 'fiction')]");
  207. List<Map<String, Object>> books2 = JsonPath.parse(json)
  208. .read("$.store.book[?(@.category == 'reference' || @.price > 10)]");
  209. print("****************books1****************");
  210. printListMap(books1);
  211. print("****************books2****************");
  212. printListMap(books1);
  213. }
  214.  
  215. private static void print(List<String> list) {
  216. for(Iterator<String> it = list.iterator();it.hasNext();) {
  217. System.out.println(it.next());
  218. }
  219. }
  220.  
  221. private static void printOb(List<Object> list) {
  222. for(Iterator<Object> it = list.iterator();it.hasNext();) {
  223. print("****");
  224. System.out.println(it.next());
  225. }
  226. }
  227.  
  228. private static void printListMap(List<Map<String, Object>> list) {
  229. for(Iterator<Map<String, Object>> it = list.iterator();it.hasNext();) {
  230. Map<String, Object> map = it.next();
  231. print("****");
  232. for(Iterator iterator =map.entrySet().iterator();iterator.hasNext();) {
  233. System.out.println(iterator.next());
  234. }
  235.  
  236. }
  237. }
  238.  
  239. private static void print(String s) {
  240. System.out.println(s);
  241. }
  242.  
  243. }

1.首先我们看getJsonValue()这个方法的输出结果:

  1. --------------------------------------getJsonValue--------------------------------------
  2. **************authors1**************
  3. Nigel Rees
  4. Evelyn Waugh
  5. Herman Melville
  6. J. R. R. Tolkien
  7. **************authors2**************
  8. Nigel Rees
  9. Evelyn Waugh
  10. Herman Melville
  11. J. R. R. Tolkien
  12. **************authors3**************
  13. [{"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}]
  14. {color=red, price=19.95}
  15. **************authors4**************
  16. 8.95
  17. 12.99
  18. 8.99
  19. 22.99
  20. 19.95
  21. **************authors5**************
  22. {category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
  23. **************authors6**************
  24. {category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}
  25. {category=fiction, author=Evelyn Waugh, title=Sword of Honour, price=12.99}
  26. **************authors7**************
  27. {category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}
  28. {category=fiction, author=Evelyn Waugh, title=Sword of Honour, price=12.99}
  29. **************authors8**************
  30. {category=fiction, author=Evelyn Waugh, title=Sword of Honour, price=12.99}
  31. **************authors9**************
  32. {category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
  33. {category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}
  34. **************authors10**************
  35. {category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
  36. {category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}
  37. **************authors11**************
  38. {category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
  39. {category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}
  40. **************authors12**************
  41. {category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}
  42. {category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
  43. **************authors13**************
  44. {category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}
  45. {category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
  46. **************authors14**************
  47. {category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}
  48. **************authors15**************
  49. {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}}
  50. 10
  51. [{"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}]
  52. {color=red, price=19.95}
  53. {category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}
  54. {category=fiction, author=Evelyn Waugh, title=Sword of Honour, price=12.99}
  55. {category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
  56. {category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}
  57. reference
  58. Nigel Rees
  59. Sayings of the Century
  60. 8.95
  61. fiction
  62. Evelyn Waugh
  63. Sword of Honour
  64. 12.99
  65. fiction
  66. Herman Melville
  67. Moby Dick
  68. 0-553-21311-3
  69. 8.99
  70. fiction
  71. J. R. R. Tolkien
  72. The Lord of the Rings
  73. 0-395-19395-8
  74. 22.99
  75. red
  76. 19.95
  77. **************authors16**************
  78. 4

2.然后看getJsonValue0()、getJsonValue1()、getJsonValue2()、getJsonValue3()、getJsonValue4()的输出结果

  1. --------------------------------------getJsonValue0--------------------------------------
  2. Nigel Rees
  3. Evelyn Waugh
  4. Herman Melville
  5. J. R. R. Tolkien
  6. --------------------------------------getJsonValue1--------------------------------------
  7. Nigel Rees
  8. Evelyn Waugh
  9. --------------------------------------getJsonValue2--------------------------------------
  10. Herman Melville
  11. J. R. R. Tolkien
  12. ****************Map****************
  13. ****
  14. category=fiction
  15. author=Evelyn Waugh
  16. title=Sword of Honour
  17. price=12.99
  18. ****
  19. category=fiction
  20. author=J. R. R. Tolkien
  21. title=The Lord of the Rings
  22. isbn=0-395-19395-8
  23. price=22.99
  24. --------------------------------------getJsonValue3--------------------------------------
  25. Nigel Rees
  26. --------------------------------------getJsonValue4--------------------------------------
  27. ****************books1****************
  28. ****
  29. category=fiction
  30. author=Herman Melville
  31. title=Moby Dick
  32. isbn=0-553-21311-3
  33. price=8.99
  34. ****************books2****************
  35. ****
  36. category=fiction
  37. author=Herman Melville
  38. title=Moby Dick
  39. isbn=0-553-21311-3
  40. 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内容的更多相关文章

  1. JSONPath解析json

    JSONPath - 用于JSON的XPath 用来解析多层嵌套的json数据;JsonPath 是一种信息抽取类库,是从JSON文档中抽取指定信息的工具. 考虑到接下来计划开发一个自动化测试平台,在 ...

  2. 使用json-path解析json

    在我们的日常开发中,有时候需要从一个json字符串中获取一个值,或者从一段json字符串中获取到某些值,如果先使用Gson或Jackson转换成java对象在获取值,有些时候是很麻烦的,那么有没有一种 ...

  3. json-path解析json方便可靠

    JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document. JsonPat ...

  4. 安卓解析json,使用BaseAdapter添加至ListView中,中间存储用JavaBean来实现

    这是一个小练习,要求解析一个提供的json文件.并将其中的id,title值获取,以ListView形式展示出来.(开发工具是android studio) 下面开始: 首先我想到的是先把json文件 ...

  5. Python | JSON 数据解析(Json & JsonPath)

    一.什么是JSON? JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式.它基于 ECMAScript (欧洲计算机协会制定的js规范)的一 ...

  6. 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 ...

  7. 使用Newtonsoft.Json.dll(JSON.NET)动态解析JSON、.net 的json的序列化与反序列化(一)

    在开发中,我非常喜欢动态语言和匿名对象带来的方便,JSON.NET具有动态序列化和反序列化任意JSON内容的能力,不必将它映射到具体的强类型对象,它可以处理不确定的类型(集合.字典.动态对象和匿名对象 ...

  8. 阶段一:通过网络请求,获得并解析JSON数据(天气应用)

    “阶段一”是指我第一次系统地学习Android开发.这主要是对我的学习过程作个记录. 在上一篇阶段一:解析JSON中提到,最近在写一个很简单的天气预报应用.即使功能很简单,但我还是想把它做成一个相对完 ...

  9. C语言创建及解析Json的使用法则

    参考原文:http://blog.csdn.net/xukai871105/article/details/33013455 JSON(JavaScriptObject Notation)是一种轻量级 ...

随机推荐

  1. 六个创建模式之简单工厂模式(Simple Factory Pattern)

    定义: 定义一个工厂类,它可以根据参数的不同生成对应的类的实例:被创建的类的实例通常有相同的父类.因为该工厂方法尝尝是静态的,所以又被称为静态工厂方法(Static Factory Method) 结 ...

  2. 二进制打印与逆序_C语言(转)

    //二进制逆序 by MoreWindows( http://blog.csdn.net/MoreWindows ) #include <stdio.h> //二进制打印函数 templa ...

  3. SQL对字符串数组的处理详解

    原文地址:SQL字符串数组操作文章出处:DIY部落(http://www.diybl.com/course/7_databases/sql/sqlServer/2007106/76999.html) ...

  4. 使用WebMatrix发布网站

    使用WebMatrix发布网站 WebMatrix 简介: Microsoft WebMatrix 是微软最新的 Web 开发工具,它包含了构建网站所需要的一切元素.您可以从开源 Web 项目或者内置 ...

  5. ALV常用参数详细描述

    调用功能模块: CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY' EXPORTING i_interface_check        = ''               ...

  6. 对抗静态分析——so文件的加密

    [预备起~~~]最近在忙找工作的事情,笔试~面试~笔试~面试...很久没有写(pian)文(gao)章(fei).忙了一阵子之后,终于~~~到了选offer的阶段(你家公司不是牛吗,老子不接你家off ...

  7. 转载 BCS 的好文章 1 - 怎么创建和使用BCS

    http://www.sharepointfabian.com/2010/04/16/how-to-create-configure-consume-sharepoint-2010-secure-st ...

  8. IOS客户端Coding项目记录(四)

    1:打开Xcode,然后闪退,报加载某库出现异常 如/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolc ...

  9. iOS 内存管理(一)之基础知识介绍

    1,什么是引用计数 所有OC对象都有一个计数器,叫做引用计数,引用计数就是目前有几个对象在使用该对象(持有该对象的引用): 2,什么是对象所有权 A对象拥有B对象的引用,A对象拥有B对象的所有权: 3 ...

  10. Android源码分析之MessageQueue

    下面让我们花些时间来看看MessageQueue的具体实现,不过在分析代码之前让我们来理解下在类开头的一大段comments. MessageQueue是比较低层的类,是持有Message(在Loop ...