1. JSONPath介绍

官网地址: https://github.com/alibaba/fastjson/wiki/JSONPath

fastjson 1.2.0之后的版本支持JSONPath。这是一个很强大的功能,可以在java框架中当作对象查询语言(OQL)来使用。

2. API

  1. package com.alibaba.fastjson;
  2. public class JSONPath {
  3. // 求值,静态方法
  4. public static Object eval(Object rootObject, String path);
  5. // 计算Size,Map非空元素个数,对象非空元素个数,Collection的Size,数组的长度。其他无法求值返回-1
  6. public static int size(Object rootObject, String path);
  7. // 是否包含,path中是否存在对象
  8. public static boolean contains(Object rootObject, String path) { }
  9. // 是否包含,path中是否存在指定值,如果是集合或者数组,在集合中查找value是否存在
  10. public static boolean containsValue(Object rootObject, String path, Object value) { }
  11. // 修改制定路径的值,如果修改成功,返回true,否则返回false
  12. public static boolean set(Object rootObject, String path, Object value) {}
  13. // 在数组或者集合中添加元素
  14. public static boolean array_add(Object rootObject, String path, Object... values);
  15. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

建议缓存JSONPath对象,这样能够提高求值的性能。

3. 支持语法

JSONPATH 描述
</td><td>根对象,例如</td><td>根对象,例如.name
[num] 数组访问,其中num是数字,可以是负数。例如$[0].leader.departments[-1].name
[num0,num1,num2…] 数组多个元素访问,其中num是数字,可以是负数,返回数组中的多个元素。例如$[0,3,-2,5]
[start:end] 数组范围访问,其中start和end是开始小表和结束下标,可以是负数,返回数组中的多个元素。例如$[0:5]
[start:end :step] 数组范围访问,其中start和end是开始小表和结束下标,可以是负数;step是步长,返回数组中的多个元素。例如$[0:5:2]
[?(key)] 对象属性非空过滤,例如$.departs[?(name)]
[key > 123] 数值类型对象属性比较过滤,例如$.departs[id >= 123],比较操作符支持=,!=,>,>=,<,<=
[key = ‘123’] 字符串类型对象属性比较过滤,例如$.departs[name = ‘123’],比较操作符支持=,!=,>,>=,<,<=
[key like ‘aa%’] 字符串类型like过滤,
例如$.departs[name like ‘sz*’],通配符只支持% 
支持not like
[key rlike ‘regexpr’] 字符串类型正则匹配过滤,
例如departs[name like ‘aa(.)*’],
正则语法为jdk的正则语法,支持not rlike
[key in (‘v0’, ‘v1’)] IN过滤, 支持字符串和数值类型 
例如: 
.departs[namein(′wenshao′,′Yako′)]<br/>.departs[namein(′wenshao′,′Yako′)]<br/>.departs[id not in (101,102)]
[key between 234 and 456] BETWEEN过滤, 支持数值类型,支持not between 
例如: 
.departs[idbetween101and201]<br/>.departs[idbetween101and201]<br/>.departs[id not between 101 and 201]
length() 或者 size() 数组长度。例如$.values.size() 
支持类型java.util.Map和java.util.Collection和数组
. 属性访问,例如$.name
.. deepScan属性访问,例如$..name
* 对象的所有属性,例如$.leader.*
[‘key’] 属性访问。例如$[‘name’]
[‘key0’,’key1’] 多个属性访问。例如$[‘id’,’name’]

以下两种写法的语义是相同的:

  1. $.store.book[0].title
  • 1

  1. $['store']['book'][0]['title']
  • 1

4. 语法示例

JSONPath 语义
$ 根对象
$[-1] 最后元素
$[:-2] 第1个至倒数第2个
$[1:] 第2个之后所有元素
$[1,2,3] 集合中1,2,3个元素

5. API 示例

5.1 例1

  1. public void test_entity() throws Exception {
  2. Entity entity = new Entity(123, new Object());
  3. Assert.assertSame(entity.getValue(), JSONPath.eval(entity, "$.value"));
  4. Assert.assertTrue(JSONPath.contains(entity, "$.value"));
  5. Assert.assertTrue(JSONPath.containsValue(entity, "$.id", 123));
  6. Assert.assertTrue(JSONPath.containsValue(entity, "$.value", entity.getValue()));
  7. Assert.assertEquals(2, JSONPath.size(entity, "$"));
  8. Assert.assertEquals(0, JSONPath.size(new Object[], "$"));
  9. }
  10. public static class Entity {
  11. private Integer id;
  12. private String name;
  13. private Object value;
  14. public Entity() {}
  15. public Entity(Integer id, Object value) { this.id = id; this.value = value; }
  16. public Entity(Integer id, String name) { this.id = id; this.name = name; }
  17. public Entity(String name) { this.name = name; }
  18. public Integer getId() { return id; }
  19. public Object getValue() { return value; }
  20. public String getName() { return name; }
  21. public void setId(Integer id) { this.id = id; }
  22. public void setName(String name) { this.name = name; }
  23. public void setValue(Object value) { this.value = value; }
  24. }
  • 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

5.2 例2

读取集合多个元素的某个属性

  1. List<Entity> entities = new ArrayList<Entity>();
  2. entities.add(new Entity("wenshao"));
  3. entities.add(new Entity("ljw2083"));
  4. List<String> names = (List<String>)JSONPath.eval(entities, "$.name"); // 返回enties的所有名称
  5. Assert.assertSame(entities.get(0).getName(), names.get(0));
  6. Assert.assertSame(entities.get(1).getName(), names.get(1));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

5.3 例3

返回集合中多个元素

  1. List<Entity> entities = new ArrayList<Entity>();
  2. entities.add(new Entity("wenshao"));
  3. entities.add(new Entity("ljw2083"));
  4. entities.add(new Entity("Yako"));
  5. List<Entity> result = (List<Entity>)JSONPath.eval(entities, "[1,2]"); // 返回下标为1和2的元素
  6. Assert.assertEquals(2, result.size());
  7. Assert.assertSame(entities.get(1), result.get(0));
  8. Assert.assertSame(entities.get(2), result.get(1));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

5.4 例4

按范围返回集合的子集

  1. List<Entity> entities = new ArrayList<Entity>();
  2. entities.add(new Entity("wenshao"));
  3. entities.add(new Entity("ljw2083"));
  4. entities.add(new Entity("Yako"));
  5. List<Entity> result = (List<Entity>)JSONPath.eval(entities, "[0:2]"); // 返回下标从0到2的元素
  6. Assert.assertEquals(3, result.size());
  7. Assert.assertSame(entities.get(0), result.get(0));
  8. Assert.assertSame(entities.get(1), result.get(1));
  9. Assert.assertSame(entities.get(2), result.get(1));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

5.5 例5

通过条件过滤,返回集合的子集

  1. List<Entity> entities = new ArrayList<Entity>();
  2. entities.add(new Entity(1001, "ljw2083"));
  3. entities.add(new Entity(1002, "wenshao"));
  4. entities.add(new Entity(1003, "yakolee"));
  5. entities.add(new Entity(1004, null));
  6. List<Object> result = (List<Object>) JSONPath.eval(entities, "[id in (1001)]");
  7. Assert.assertEquals(1, result.size());
  8. Assert.assertSame(entities.get(0), result.get(0));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

5.6 例6

根据属性值过滤条件判断是否返回对象,修改对象,数组属性添加元素

  1. Entity entity = new Entity(1001, "ljw2083");
  2. Assert.assertSame(entity , JSONPath.eval(entity, "[id = 1001]"));
  3. Assert.assertNull(JSONPath.eval(entity, "[id = 1002]"));
  4. JSONPath.set(entity, "id", 123456); //将id字段修改为123456
  5. Assert.assertEquals(123456, entity.getId().intValue());
  6. JSONPath.set(entity, "value", new int[0]); //将value字段赋值为长度为0的数组
  7. JSONPath.arrayAdd(entity, "value", 1, 2, 3); //将value字段的数组添加元素1,2,3
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

5.7 例7

  1. Map root = Collections.singletonMap("company", //
  2. Collections.singletonMap("departs", //
  3. Arrays.asList( //
  4. Collections.singletonMap("id",
  5. 1001), //
  6. Collections.singletonMap("id",
  7. 1002), //
  8. Collections.singletonMap("id", 1003) //
  9. ) //
  10. ));
  11. List<Object> ids = (List<Object>) JSONPath.eval(root, "$..id");
  12. assertEquals(3, ids.size());
  13. assertEquals(1001, ids.get(0));
  14. assertEquals(1002, ids.get(1));
  15. assertEquals(1003, ids.get(2));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

具体用例测试请看下面:

  1. /**
  2. * @author itguang
  3. * @create 2017-12-10 10:03
  4. **/
  5. @RunWith(SpringRunner.class)
  6. @SpringBootTest
  7. @Slf4j
  8. public class JSONpathControllerTest {
  9. @Test
  10. public void test() {
  11. User user = new User("itguang", "123456", "123@qq.com");
  12. String username = (String) JSONPath.eval(user, "$.username");
  13. log.info("$.username = {}", username);
  14. Entity entity = new Entity(123, user);
  15. User user1 = (User) JSONPath.eval(entity, "$.value");
  16. log.info("user={}", user1.toString());
  17. }
  18. @Test
  19. public void test2() {
  20. User user = new User("itguang", "123456", "123@qq.com");
  21. Entity entity = new Entity(123, user);
  22. //判断entity中是否有 data
  23. boolean contains = JSONPath.contains(entity, "$.data");
  24. Assert.assertTrue(contains);
  25. //判断 entity.data.username 属性值是否为 itguang
  26. boolean containsValue = JSONPath.containsValue(entity, "$.data.username", "itguang");
  27. Assert.assertTrue(containsValue);
  28. Assert.assertEquals(2, JSONPath.size(entity, "$"));
  29. }
  30. @Test
  31. public void test3() {
  32. List<Entity> entities = new ArrayList<Entity>();
  33. entities.add(new Entity("逻辑"));
  34. entities.add(new Entity("叶文杰"));
  35. entities.add(new Entity("程心"));
  36. //返回集合中多个元素
  37. List<String> names = (List<String>) JSONPath.eval(entities, "$.name");
  38. log.info("返回集合中多个元素names={}", names);
  39. //返回下标 0 和 2 的元素
  40. List<Entity> result = (List<Entity>) JSONPath.eval(entities, "[0,2]");
  41. log.info("返回下标 0 和 2 的元素={}", result);
  42. // 返回下标从0到2的元素
  43. List<Entity> result2 = (List<Entity>) JSONPath.eval(entities, "[0:2]");
  44. log.info("返回下标从0到2的元素={}", result2);
  45. }
  46. @Test
  47. public void test4() {
  48. List<Entity> entities = new ArrayList<Entity>();
  49. entities.add(new Entity(1001, "逻辑"));
  50. entities.add(new Entity(1002, "程心"));
  51. entities.add(new Entity(1003, "叶文杰"));
  52. entities.add(new Entity(1004, null));
  53. //通过条件过滤,返回集合的子集
  54. List<Entity> result = (List<Entity>) JSONPath.eval(entities, "[id in (1001)]");
  55. log.info("通过条件过滤,返回集合的子集={}", result);
  56. }
  57. /**
  58. * 使用JSONPrase 解析JSON字符串或者Object对象
  59. * <p>
  60. * read(String json, String path)//直接使用json字符串匹配
  61. * <p>
  62. * eval(Object rootObject, String path) //直接使用 对象匹配
  63. * <p>
  64. * <p>
  65. * {"store":{"bicycle":{"color":"red","price":19.95},"book":[{"author":"Nigel Rees","price":8.95,"category":"reference","title":"Sayings of the Century"},{"author":"Evelyn Waugh","price":12.99,"isbn":"0-553-21311-3","category":"fiction","title":"Sword of Honour"}]}}
  66. */
  67. @Test
  68. public void test5() {
  69. String jsonStr = "{\n" +
  70. " \"store\": {\n" +
  71. " \"bicycle\": {\n" +
  72. " \"color\": \"red\",\n" +
  73. " \"price\": 19.95\n" +
  74. " },\n" +
  75. " \"book\": [\n" +
  76. " {\n" +
  77. " \"author\": \"刘慈欣\",\n" +
  78. " \"price\": 8.95,\n" +
  79. " \"category\": \"科幻\",\n" +
  80. " \"title\": \"三体\"\n" +
  81. " },\n" +
  82. " {\n" +
  83. " \"author\": \"itguang\",\n" +
  84. " \"price\": 12.99,\n" +
  85. " \"category\": \"编程语言\",\n" +
  86. " \"title\": \"go语言实战\"\n" +
  87. " }\n" +
  88. " ]\n" +
  89. " }\n" +
  90. "}";
  91. JSONObject jsonObject = JSON.parseObject(jsonStr);
  92. log.info(jsonObject.toString());
  93. //得到所有的书
  94. List<Book> books = (List<Book>) JSONPath.eval(jsonObject, "$.store.book");
  95. log.info("books={}", books);
  96. //得到所有的书名
  97. List<String> titles = (List<String>) JSONPath.eval(jsonObject, "$.store.book.title");
  98. log.info("titles={}", titles);
  99. //第一本书title
  100. String title = (String) JSONPath.read(jsonStr, "$.store.book[0].title");
  101. log.info("title={}", title);
  102. //price大于10元的book
  103. List<Book> list = (List<Book>) JSONPath.read(jsonStr, "$.store.book[price > 10]");
  104. log.info("price大于10元的book={}",list);
  105. //price大于10元的title
  106. List<String> list2 =(List<String>) JSONPath.read(jsonStr, "$.store.book[price > 10].title");
  107. log.info("price大于10元的title={}",list2);
  108. //category(类别)为科幻的book
  109. List<Book> list3 = (List<Book>) JSONPath.read(jsonStr,"$.store.book[category = '科幻']");
  110. log.info("category(类别)为科幻的book={}",list3);
  111. //bicycle的所有属性值
  112. Collection<String> values = (Collection<String>) JSONPath.eval(jsonObject, "$.store.bicycle.*");
  113. log.info("bicycle的所有属性值={}",values);
  114. //bicycle的color和price属性值
  115. List<String> read =(List<String>) JSONPath.read(jsonStr, "$.store.bicycle['color','price']");
  116. log.info("bicycle的color和price属性值={}",read);
  117. }
  118. }
  • 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
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174

源码地址: https://github.com/itguang/gitbook-smile/blob/master/springboot-fastjson/fastjson%E4%B9%8BJSONPath%E4%BD%BF%E7%94%A8.md

 

fastJson 之 JSONPath使用的更多相关文章

  1. alibaba/fastjson 之 JSONPath

    JOSNPath 是一个非常强大的工具,对于处理 json 对象非常方便. 官方地址:https://github.com/alibaba/fastjson/wiki/JSONPath 基本用法:ht ...

  2. JSONPath介绍

    1. JSONPath介绍 官网地址: https://github.com/alibaba/fastjson/wiki/JSONPath fastjson 1.2.0之后的版本支持JSONPath. ...

  3. 【技术累积】【点】【java】【1】JSONPath

    闲聊 以后周中每天一篇这种偏短的文章,周末就发长一点的文章,不然自己实在是懒,懒成了习惯了... 开始 首先需要明确的是,这里说的是阿里巴巴的fastjson包中的JSONPath,不是jsonPat ...

  4. Jackson替换fastjson

    为什么要替换fastjson 工程里大量使用了fastjson作为序列化和反序列化框架,甚至ORM在处理部分字段也依赖fastjson进行序列化和反序列化.那么作为大量使用的基础框架,为什么还要进行替 ...

  5. JSON path

    https://github.com/itguang/gitbook-smile/blob/master/springboot-fastjson/fastjson%E4%B9%8BJSONPath%E ...

  6. 自定义springmvc参数解析器

    实现spring HandlerMethodArgumentResolver接口 通过使用@JsonArg自定义注解来解析json数据(通过fastjson的jsonPath),支持多个参数(@Req ...

  7. 想在java接口自动化里用上Python的requests?这样做就可以了

    相信现在很多的公司自动化测试重点都在接口层,因为接口测试更加接近代码底层,相对于UI自动化,接口自动化有着开发更快.覆盖更全.回报率高等优点. 接口自动化代码实现不难,本质上就是代码模拟发送请求,然后 ...

  8. JSONPath使用

    JSONPath是fastjson在1.2.0之后支持的.JSONPath是一个很强大的功能.关于JSONPath的介绍请查看官方文档 JSONPath. 官方文档上给出了详细的说明以及使用.但是官方 ...

  9. Fastjson 专题

    JSONObject.toJSONString(Object object, SerializerFeature... features) SerializerFeature有用的一些枚举值 Quot ...

随机推荐

  1. canvas-8searchLight4.html

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  2. JS之document.cookie详解以及$.cookie的使用

    什么是cookie? cookie 是存储于访问者的计算机中的变量.每当同一台计算机通过浏览器请求某个页面时,就会发送这个 cookie.你可以使用 JavaScript 来创建和取回 cookie ...

  3. apache配置-html碎片shtml格式

    修改SSI 文件 conf–httpd.conf <Directory "D:/Android/Apache2.2/htdocs">  //修改文件目录 # # Pos ...

  4. maven 术语

    1, 中央仓库 是一个网络仓库, 用于存储各种 jar 和 maven 插件, 官方网站显示的是列表, 不友好, 一般搜索依赖到一个三方地址: https://mvnrepository.com/ 2 ...

  5. Javascript 流程控制

    流程控制 JavaScript通过流程语句来执行程序流,程序流有若干语句组成.在正常情况下,程序中 的语句时按照书写顺序执行的,这种结构称为顺序结构.除了顺序结构之外还有选择结构和循环结构. 1.选择 ...

  6. C# 对象持久化

    本文以一个简单的小例子,简述对象持久化的相关知识,仅供学习分享使用,如有不足之处,还请指正. 概述 对象持久化是指将内存中的对象保存到可永久保存的存储设备中(如磁盘)的一种技术. 本文介绍的是除数据库 ...

  7. C# Partial:分部方法和分部类

    using System; namespace Partial { class Program { static void Main(string[] args) { A a = new A(); } ...

  8. (网页)angularJs中怎么模拟jQuery中的this?(转)

    转载自mini_fan博客园: 今天想在Angular项目中使用jQuery的this功能,发现undefined.代码如下: HTML部分: <p ng-click="testCli ...

  9. 深圳共创力“研发管理&知识管理”高端研讨交流会在深圳举办!

    2017/4/8,由深圳市共创力企业管理咨询公司举办的“研发管理&知识管理”高端研讨会在深圳市南山区圣淘沙国际酒店(翡翠店)隆重召开.此次研讨会由共创力总经理.首席顾问杨学明先生主持.研讨会先 ...

  10. 乱码问题-页面跳转方式-Servlet配置文件

    1.HttpServletRequest a)HttpServletRequest是一个接口,继承了ServletRequest接口: b)HttpServletRequest对象由服务器创建,并作为 ...