当前位置:   article > 正文

JsonPath | FastJson的JSONPath使用_fastjson jsonpath

fastjson jsonpath

一. 简介

JSONPath - 用于JSON的XPath

用来解析多层嵌套的json数据;JsonPath 是一种信息抽取类库,是从JSON文档中抽取指定信息的工具.

 JsonPath有许多编程语言,如Javascript、Python、PHP、Java等

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

 JSONPath GitHubhttps://github.com/json-path/JsonPath 

JsonPath表达式始终引用JSON结构,其方式与XPath表达式与XML文档结合使用的方式相同。$无论是对象还是数组,JsonPath中的“根成员对象”始终被称为。

JsonPath表达式可以使用点表示法

$.store.book[0].title

或括号表示法

$['store']['book'][0]['title']

 二、API

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

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

三、支持语法

JSONPATH描述
</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[id not in (101,102)]
[key between 234 and 456]BETWEEN过滤, 支持数值类型,支持not between 
例如: 
.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’]

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

$.store.book[0].title

$['store']['book'][0]['title']

四、语法示例

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

五、API示例

5.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. }

5.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));

5.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));

 5.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));

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));

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

5.7 具体用例测试

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. @Slf4j
  4. public class JSONpathControllerTest {
  5. @Test
  6. public void test() {
  7. User user = new User("itguang", "123456", "123@qq.com");
  8. String username = (String) JSONPath.eval(user, "$.username");
  9. log.info("$.username = {}", username);
  10. Entity entity = new Entity(123, user);
  11. User user1 = (User) JSONPath.eval(entity, "$.value");
  12. log.info("user={}", user1.toString());
  13. }
  14. @Test
  15. public void test2() {
  16. User user = new User("itguang", "123456", "123@qq.com");
  17. Entity entity = new Entity(123, user);
  18. //判断entity中是否有 data
  19. boolean contains = JSONPath.contains(entity, "$.data");
  20. Assert.assertTrue(contains);
  21. //判断 entity.data.username 属性值是否为 itguang
  22. boolean containsValue = JSONPath.containsValue(entity, "$.data.username", "itguang");
  23. Assert.assertTrue(containsValue);
  24. Assert.assertEquals(2, JSONPath.size(entity, "$"));
  25. }
  26. @Test
  27. public void test3() {
  28. List<Entity> entities = new ArrayList<Entity>();
  29. entities.add(new Entity("逻辑"));
  30. entities.add(new Entity("叶文杰"));
  31. entities.add(new Entity("程心"));
  32. //返回集合中多个元素
  33. List<String> names = (List<String>) JSONPath.eval(entities, "$.name");
  34. log.info("返回集合中多个元素names={}", names);
  35. //返回下标 0 和 2 的元素
  36. List<Entity> result = (List<Entity>) JSONPath.eval(entities, "[0,2]");
  37. log.info("返回下标 0 和 2 的元素={}", result);
  38. // 返回下标从0到2的元素
  39. List<Entity> result2 = (List<Entity>) JSONPath.eval(entities, "[0:2]");
  40. log.info("返回下标从0到2的元素={}", result2);
  41. }
  42. @Test
  43. public void test4() {
  44. List<Entity> entities = new ArrayList<Entity>();
  45. entities.add(new Entity(1001, "逻辑"));
  46. entities.add(new Entity(1002, "程心"));
  47. entities.add(new Entity(1003, "叶文杰"));
  48. entities.add(new Entity(1004, null));
  49. //通过条件过滤,返回集合的子集
  50. List<Entity> result = (List<Entity>) JSONPath.eval(entities, "[id in (1001)]");
  51. log.info("通过条件过滤,返回集合的子集={}", result);
  52. }
  53. /**
  54. * 使用JSONPrase 解析JSON字符串或者Object对象
  55. * <p>
  56. * read(String json, String path)//直接使用json字符串匹配
  57. * <p>
  58. * eval(Object rootObject, String path) //直接使用 对象匹配
  59. * <p>
  60. * <p>
  61. * {"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"}]}}
  62. */
  63. @Test
  64. public void test5() {
  65. String jsonStr = "{\n" +
  66. " \"store\": {\n" +
  67. " \"bicycle\": {\n" +
  68. " \"color\": \"red\",\n" +
  69. " \"price\": 19.95\n" +
  70. " },\n" +
  71. " \"book\": [\n" +
  72. " {\n" +
  73. " \"author\": \"刘慈欣\",\n" +
  74. " \"price\": 8.95,\n" +
  75. " \"category\": \"科幻\",\n" +
  76. " \"title\": \"三体\"\n" +
  77. " },\n" +
  78. " {\n" +
  79. " \"author\": \"itguang\",\n" +
  80. " \"price\": 12.99,\n" +
  81. " \"category\": \"编程语言\",\n" +
  82. " \"title\": \"go语言实战\"\n" +
  83. " }\n" +
  84. " ]\n" +
  85. " }\n" +
  86. "}";
  87. JSONObject jsonObject = JSON.parseObject(jsonStr);
  88. log.info(jsonObject.toString());
  89. //得到所有的书
  90. List<Book> books = (List<Book>) JSONPath.eval(jsonObject, "$.store.book");
  91. log.info("books={}", books);
  92. //得到所有的书名
  93. List<String> titles = (List<String>) JSONPath.eval(jsonObject, "$.store.book.title");
  94. log.info("titles={}", titles);
  95. //第一本书title
  96. String title = (String) JSONPath.read(jsonStr, "$.store.book[0].title");
  97. log.info("title={}", title);
  98. //price大于10元的book
  99. List<Book> list = (List<Book>) JSONPath.read(jsonStr, "$.store.book[price > 10]");
  100. log.info("price大于10元的book={}",list);
  101. //price大于10元的title
  102. List<String> list2 =(List<String>) JSONPath.read(jsonStr, "$.store.book[price > 10].title");
  103. log.info("price大于10元的title={}",list2);
  104. //category(类别)为科幻的book
  105. List<Book> list3 = (List<Book>) JSONPath.read(jsonStr,"$.store.book[category = '科幻']");
  106. log.info("category(类别)为科幻的book={}",list3);
  107. //bicycle的所有属性值
  108. Collection<String> values = (Collection<String>) JSONPath.eval(jsonObject, "$.store.bicycle.*");
  109. log.info("bicycle的所有属性值={}",values);
  110. //bicycle的color和price属性值
  111. List<String> read =(List<String>) JSONPath.read(jsonStr, "$.store.bicycle['color','price']");
  112. log.info("bicycle的color和price属性值={}",read);
  113. }
  114. }

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/991124
推荐阅读
相关标签
  

闽ICP备14008679号