fastJson之JSONPath使用(转)

2024-01-21 17:59
文章标签 使用 fastjson jsonpath

本文主要是介绍fastJson之JSONPath使用(转),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

fastJson之JSONPath使用(转)

1. JSONPath介绍

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

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

2. API

复制代码
package com.alibaba.fastjson;public class JSONPath {          //  求值,静态方法public static Object eval(Object rootObject, String path);// 计算Size,Map非空元素个数,对象非空元素个数,Collection的Size,数组的长度。其他无法求值返回-1public static int size(Object rootObject, String path);// 是否包含,path中是否存在对象public static boolean contains(Object rootObject, String path) { }// 是否包含,path中是否存在指定值,如果是集合或者数组,在集合中查找value是否存在public static boolean containsValue(Object rootObject, String path, Object value) { }// 修改制定路径的值,如果修改成功,返回true,否则返回falsepublic static boolean set(Object rootObject, String path, Object value) {}// 在数组或者集合中添加元素public static boolean array_add(Object rootObject, String path, Object... values);
}
复制代码

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

3. 支持语法

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']

4. 语法示例

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

5. API 示例

5.1 例1

复制代码
public void test_entity() throws Exception {Entity entity = new Entity(123, new Object());Assert.assertSame(entity.getValue(), JSONPath.eval(entity, "$.value")); Assert.assertTrue(JSONPath.contains(entity, "$.value"));Assert.assertTrue(JSONPath.containsValue(entity, "$.id", 123));Assert.assertTrue(JSONPath.containsValue(entity, "$.value", entity.getValue())); Assert.assertEquals(2, JSONPath.size(entity, "$"));Assert.assertEquals(0, JSONPath.size(new Object[], "$")); 
}public static class Entity {private Integer id;private String name;private Object value;public Entity() {}public Entity(Integer id, Object value) { this.id = id; this.value = value; }public Entity(Integer id, String name) { this.id = id; this.name = name; }public Entity(String name) { this.name = name; }public Integer getId() { return id; }public Object getValue() { return value; }        public String getName() { return name; }public void setId(Integer id) { this.id = id; }public void setName(String name) { this.name = name; }public void setValue(Object value) { this.value = value; }
}
复制代码

5.2 例2

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

复制代码
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity("wenshao"));
entities.add(new Entity("ljw2083"));List<String> names = (List<String>)JSONPath.eval(entities, "$.name"); // 返回enties的所有名称
Assert.assertSame(entities.get(0).getName(), names.get(0));
Assert.assertSame(entities.get(1).getName(), names.get(1));
复制代码

5.3 例3

返回集合中多个元素

复制代码
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity("wenshao"));
entities.add(new Entity("ljw2083"));
entities.add(new Entity("Yako"));List<Entity> result = (List<Entity>)JSONPath.eval(entities, "[1,2]"); // 返回下标为1和2的元素
Assert.assertEquals(2, result.size());
Assert.assertSame(entities.get(1), result.get(0));
Assert.assertSame(entities.get(2), result.get(1));
复制代码

5.4 例4

按范围返回集合的子集

复制代码
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity("wenshao"));
entities.add(new Entity("ljw2083"));
entities.add(new Entity("Yako"));List<Entity> result = (List<Entity>)JSONPath.eval(entities, "[0:2]"); // 返回下标从0到2的元素
Assert.assertEquals(3, result.size());
Assert.assertSame(entities.get(0), result.get(0));
Assert.assertSame(entities.get(1), result.get(1));
Assert.assertSame(entities.get(2), result.get(1));
复制代码

5.5 例5

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

复制代码
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity(1001, "ljw2083"));
entities.add(new Entity(1002, "wenshao"));
entities.add(new Entity(1003, "yakolee"));
entities.add(new Entity(1004, null));List<Object> result = (List<Object>) JSONPath.eval(entities, "[id in (1001)]");
Assert.assertEquals(1, result.size());
Assert.assertSame(entities.get(0), result.get(0));
复制代码

5.6 例6

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

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

5.7 例7

复制代码
Map root = Collections.singletonMap("company", //
                                    Collections.singletonMap("departs", //
                                                             Arrays.asList( //
                                                                            Collections.singletonMap("id",1001), //
                                                                            Collections.singletonMap("id",1002), //
                                                                            Collections.singletonMap("id", 1003) //
                                                             ) //
                                    ));List<Object> ids = (List<Object>) JSONPath.eval(root, "$..id");
assertEquals(3, ids.size());
assertEquals(1001, ids.get(0));
assertEquals(1002, ids.get(1));
assertEquals(1003, ids.get(2));
复制代码

具体用例测试请看下面:

复制代码
/*** @author itguang* @create 2017-12-10 10:03**/@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class JSONpathControllerTest {@Testpublic void test() {User user = new User("itguang", "123456", "123@qq.com");String username = (String) JSONPath.eval(user, "$.username");log.info("$.username = {}", username);Entity entity = new Entity(123, user);User user1 = (User) JSONPath.eval(entity, "$.value");log.info("user={}", user1.toString());}@Testpublic void test2() {User user = new User("itguang", "123456", "123@qq.com");Entity entity = new Entity(123, user);//判断entity中是否有 databoolean contains = JSONPath.contains(entity, "$.data");Assert.assertTrue(contains);//判断 entity.data.username 属性值是否为 itguangboolean containsValue = JSONPath.containsValue(entity, "$.data.username", "itguang");Assert.assertTrue(containsValue);Assert.assertEquals(2, JSONPath.size(entity, "$"));}@Testpublic void test3() {List<Entity> entities = new ArrayList<Entity>();entities.add(new Entity("逻辑"));entities.add(new Entity("叶文杰"));entities.add(new Entity("程心"));//返回集合中多个元素List<String> names = (List<String>) JSONPath.eval(entities, "$.name");log.info("返回集合中多个元素names={}", names);//返回下标 0 和 2 的元素List<Entity> result = (List<Entity>) JSONPath.eval(entities, "[0,2]");log.info("返回下标 0 和 2 的元素={}", result);// 返回下标从0到2的元素List<Entity> result2 = (List<Entity>) JSONPath.eval(entities, "[0:2]");log.info("返回下标从0到2的元素={}", result2);}@Testpublic void test4() {List<Entity> entities = new ArrayList<Entity>();entities.add(new Entity(1001, "逻辑"));entities.add(new Entity(1002, "程心"));entities.add(new Entity(1003, "叶文杰"));entities.add(new Entity(1004, null));//通过条件过滤,返回集合的子集
List<Entity> result = (List<Entity>) JSONPath.eval(entities, "[id in (1001)]");log.info("通过条件过滤,返回集合的子集={}", result);}/*** 使用JSONPrase 解析JSON字符串或者Object对象* <p>* read(String json, String path)//直接使用json字符串匹配* <p>* eval(Object rootObject, String path) //直接使用 对象匹配* <p>* <p>* {"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"}]}}*/@Testpublic void test5() {String jsonStr = "{\n" +"    \"store\": {\n" +"        \"bicycle\": {\n" +"            \"color\": \"red\",\n" +"            \"price\": 19.95\n" +"        },\n" +"        \"book\": [\n" +"            {\n" +"                \"author\": \"刘慈欣\",\n" +"                \"price\": 8.95,\n" +"                \"category\": \"科幻\",\n" +"                \"title\": \"三体\"\n" +"            },\n" +"            {\n" +"                \"author\": \"itguang\",\n" +"                \"price\": 12.99,\n" +"                \"category\": \"编程语言\",\n" +"                \"title\": \"go语言实战\"\n" +"            }\n" +"        ]\n" +"    }\n" +"}";JSONObject jsonObject = JSON.parseObject(jsonStr);log.info(jsonObject.toString());//得到所有的书List<Book> books = (List<Book>) JSONPath.eval(jsonObject, "$.store.book");log.info("books={}", books);//得到所有的书名List<String> titles = (List<String>) JSONPath.eval(jsonObject, "$.store.book.title");log.info("titles={}", titles);//第一本书titleString title = (String) JSONPath.read(jsonStr, "$.store.book[0].title");log.info("title={}", title);//price大于10元的bookList<Book> list = (List<Book>) JSONPath.read(jsonStr, "$.store.book[price > 10]");log.info("price大于10元的book={}",list);//price大于10元的titleList<String> list2 =(List<String>) JSONPath.read(jsonStr, "$.store.book[price > 10].title");log.info("price大于10元的title={}",list2);//category(类别)为科幻的bookList<Book> list3 = (List<Book>) JSONPath.read(jsonStr,"$.store.book[category = '科幻']");log.info("category(类别)为科幻的book={}",list3);//bicycle的所有属性值
Collection<String> values = (Collection<String>) JSONPath.eval(jsonObject, "$.store.bicycle.*");log.info("bicycle的所有属性值={}",values);//bicycle的color和price属性值List<String> read =(List<String>) JSONPath.read(jsonStr, "$.store.bicycle['color','price']");log.info("bicycle的color和price属性值={}",read);}}
复制代码
源码地址: https://github.com/itguang/gitbook-smile/blob/master/springboot-fastjson/fastjson%E4%B9%8BJSONPath%E4%BD%BF%E7%94%A8.md

转自:http://blog.csdn.net/itguangit/article/details/78764212

这篇关于fastJson之JSONPath使用(转)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/630377

相关文章

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁

ModelMapper基本使用和常见场景示例详解

《ModelMapper基本使用和常见场景示例详解》ModelMapper是Java对象映射库,支持自动映射、自定义规则、集合转换及高级配置(如匹配策略、转换器),可集成SpringBoot,减少样板... 目录1. 添加依赖2. 基本用法示例:简单对象映射3. 自定义映射规则4. 集合映射5. 高级配置匹

Spring 框架之Springfox使用详解

《Spring框架之Springfox使用详解》Springfox是Spring框架的API文档工具,集成Swagger规范,自动生成文档并支持多语言/版本,模块化设计便于扩展,但存在版本兼容性、性... 目录核心功能工作原理模块化设计使用示例注意事项优缺点优点缺点总结适用场景建议总结Springfox 是

嵌入式数据库SQLite 3配置使用讲解

《嵌入式数据库SQLite3配置使用讲解》本文强调嵌入式项目中SQLite3数据库的重要性,因其零配置、轻量级、跨平台及事务处理特性,可保障数据溯源与责任明确,详细讲解安装配置、基础语法及SQLit... 目录0、惨痛教训1、SQLite3环境配置(1)、下载安装SQLite库(2)、解压下载的文件(3)、

使用Python绘制3D堆叠条形图全解析

《使用Python绘制3D堆叠条形图全解析》在数据可视化的工具箱里,3D图表总能带来眼前一亮的效果,本文就来和大家聊聊如何使用Python实现绘制3D堆叠条形图,感兴趣的小伙伴可以了解下... 目录为什么选择 3D 堆叠条形图代码实现:从数据到 3D 世界的搭建核心代码逐行解析细节优化应用场景:3D 堆叠图

Springboot如何正确使用AOP问题

《Springboot如何正确使用AOP问题》:本文主要介绍Springboot如何正确使用AOP问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录​一、AOP概念二、切点表达式​execution表达式案例三、AOP通知四、springboot中使用AOP导出

Navicat数据表的数据添加,删除及使用sql完成数据的添加过程

《Navicat数据表的数据添加,删除及使用sql完成数据的添加过程》:本文主要介绍Navicat数据表的数据添加,删除及使用sql完成数据的添加过程,具有很好的参考价值,希望对大家有所帮助,如有... 目录Navicat数据表数据添加,删除及使用sql完成数据添加选中操作的表则出现如下界面,查看左下角从左

python 常见数学公式函数使用详解(最新推荐)

《python常见数学公式函数使用详解(最新推荐)》文章介绍了Python的数学计算工具,涵盖内置函数、math/cmath标准库及numpy/scipy/sympy第三方库,支持从基础算术到复杂数... 目录python 数学公式与函数大全1. 基本数学运算1.1 算术运算1.2 分数与小数2. 数学函数