alibaba/fastjson之jsonpath(代码片段)

stormlong stormlong     2022-12-12     571

关键词:

JOSNPath 是一个非常强大的工具,对于处理 json 对象非常方便。

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

基本用法:https://blog.csdn.net/itguangit/article/details/78764212

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

     //  求值,静态方法,按需计算,性能更好
     public static Object extract(String json, String path);
     
     // 计算Size,Map非空元素个数,对象非空元素个数,Collection的Size,数组的长度。其他无法求值返回-1
     public 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,否则返回false
     public static boolean set(Object rootObject, String path, Object value) 

     // 在数组或者集合中添加元素
     public static boolean arrayAdd(Object rootObject, String path, Object... values);
     
     // 获取,Map的KeySet,对象非空属性的名称。数组、Collection等不支持类型返回null。
     public static Set<?> keySet(Object rootObject, String path);

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

3. 支持语法

JSONPATH 描述
$ 根对象,例如$.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[name in (‘wenshao‘,‘Yako‘)] 
$.departs[id not in (101,102)]
[key between 234 and 456] BETWEEN过滤, 支持数值类型,支持not between 
例如: 
$.departs[id between 101 and 201]
$.departs[id not between 101 and 201]
length() 或者 size() 数组长度。例如$.values.size() 
支持类型java.util.Map和java.util.Collection和数组
keySet() 获取Map的keySet或者对象的非空属性名称。例如$.val.keySet() 
支持类型:Map和普通对象
不支持:Collection和数组(返回null)
. 属性访问,例如$.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));

5.8 例8 keySet

使用keySet抽取对象的属性名,null值属性的名字并不包含在keySet结果中,使用时需要注意,详细可参考示例。

Entity e = new Entity();
e.setId(null);
e.setName("hello");
Map<String, Entity> map = Collections.singletonMap("e", e);
Collection<String> result;

// id is null, excluded by keySet
result = (Collection<String>)JSONPath.eval(map, "$.e.keySet()");
assertEquals(1, result.size());
Assert.assertTrue(result.contains("name"));

e.setId(1L);
result = (Collection<String>)JSONPath.eval(map, "$.e.keySet()");
Assert.assertEquals(2, result.size());
Assert.assertTrue(result.contains("id")); // included
Assert.assertTrue(result.contains("name"));

// Same result
Assert.assertEquals(result, JSONPath.keySet(map, "$.e"));
Assert.assertEquals(result, new JSONPath("$.e").keySet(map));

再见fastjson!fastjson2正式发布,性能炸裂…

点击关注公众号,Java干货及时送达1.FASTJSON2.0介绍FASTJSON2.0是FASTJSON项目的重要升级,目标是为下一个十年提供一个高性能的JSON库,同一套API支持JSON/JSONB两种协议,JSONPath是一等公民,支持全量解析和部分解析&... 查看详情

com.alibaba.fastjson.jsonobject

packagecom.alibaba.fastjson;importjava.util.Date;importjava.util.List;importcom.alibaba.fastjson.componet.Grade;importcom.alibaba.fastjson.componet.User;importcom.alibaba.fastjson.serializer.Serialize 查看详情

com.alibaba.fastjson.jsonobjectcannotbecasttocom.alibaba.fastjson.jsonobject

...,当时服务器上运行正常,运行环境都是JDK8:com.alibaba.fastjson.JSONObjectcannotbecasttocom.alibaba.fastjson.JSONObject后面我尝试切换JDK11,这时候报错信息更全面了,发现原来是RestartClassLoader的锅:classcom.alibaba.fastjson.JSONObjectcannotbecasttoclassc... 查看详情

com.alibaba.fastjson设置时区

参考技术Acom.alibaba.fastjson设置时区方法。1、FastJson配置FastJson基础知识点击前往。2、SpringBoot整合FastJson点击前往。3、导入FastJson依赖fastjson。 查看详情

springmvc+fastjson之时间类型序列化

时间类型序列化:注意红色代码,必须引入fastjson的JSONField类,而非其它。importcom.alibaba.fastjson.annotation.JSONField;@Entity@Table(name="User")publicclassUser{  @Id  @Column(name="id")  @GeneratedValue(strategy=GenerationType 查看详情

fastjson

fastJson 下载地址:https://github.com/alibaba/fastjson/ fastjson主要的API哪些?fastjson入口类是com.alibaba.fastjson.JSON,主要的API是JSON.toJSONString,和parseObject。packagecom.alibaba.fastjson;publicabstractclas 查看详情

com.alibaba.fastjson.jsonexception:syntaxerror,expect[,actualintstack

com.alibaba.fastjson.JSONException:syntaxerror,expect[,actualintStacktrace: 这个json解析错误,怎么解决com.alibaba.fastjson.JSONException:syntaxerror,expect[,actualint atcom.alibaba.fastjson.parser.AbstractJSONParser.parseArray(AbstractJSONParser.java:57) atcom.alibaba.fastjson.parser.Abst... 查看详情

com.alibaba.fastjson.jsonarray哪个包

参考技术Acom.alibaba.fastjson.jsonarray这个包下面<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.4</version></dependency>本回答被提问者采纳 查看详情

com.alibaba.fastjson.jsonexception:autotypeisnotsupport.

解决办法:https://github.com/alibaba/fastjson/wiki/enable_autotype文摘如下:一、添加autotype白名单添加白名单有三种方式,三选一,如下:1.在代码中配置ParserConfig.getGlobalInstance().addAccept("com.taobao.pac.client.sdk.dataobject.");如果有多个包名前缀 查看详情

fastjson解析错误.jsonexception:roundingnecessary

参考技术A解析报错:com.alibaba.fastjson.JSONException:Roundingnecessaryatcom.alibaba.fastjson.parser.DefaultJSONParser.parseObject(DefaultJSONParser.java:708)atcom.alibaba.fastjson.parser.DefaultJSONParser.parseObject(DefaultJSONParser.java:677)atcom.alibaba.fastjson.JSON.parseObject(JSON.j... 查看详情

json三-------com.alibaba.fastjson

1.需要阿里巴巴的fastjson.jar2.将json字符串转为JSONObject,通过JSONObject.parseObject(json字符串),取值的话通过json对象的getString(),getIntValue()等等获取JSONObject的值Stringstudent="{‘name‘:‘张三‘,‘age‘:30}";JSONObjectjson=JSONObject.par 查看详情

defaultconstructornotfound异常解决方法(代码片段)

Exceptioninthread"Thread-13"com.alibaba.fastjson.JSONException:defaultconstructornotfound.classcom.nowcoder.async.EventModel atcom.alibaba.fastjson.util.JavaBeanInfo.build(JavaBeanInfo.java:212) atcom.alibaba.fastjson.parser.ParserConfig.createJavaBeanDeserializer(ParserConfig.java:504) atco... 查看详情

json工具类库:alibaba/fastjson使用记录

JSON工具类库:alibaba/fastjson使用记录一、了解JSONJSON标准规范中文文档:http://www.json.org/json-zh.html最佳实践:http://kimmking.github.io/2017/06/06/json-best-practice/(JSON的高级使用,特别十分有参考价值)二、项目地址和Wiki:Git地址:https://... 查看详情

failedtoresolve:com.alibaba:fastjson:1.2.76.android(代码片段)

添加fastjson失败,gradle报错RTFailedtoresolve:com.alibaba:fastjson:1.2.76.androidShowinProjectStructuredialogAffectedModules:app查询https://maven.aliyun.com/mvn/search这个发现并不存在1.2.76.android这个包…虽然FastJson官方写着但是 查看详情

fastjson解析报错com.alibaba.fastjson.jsonexception:createinstanceerror...

用fastJson解析报createinstanceerror的错误 认真检查,bean类内的字段都和服务端返回的字段一致,格式都是正确的,为什么会报错呢。 在网上找到答案,如果存在内嵌的情况:报错代码:publicclass A     privateStri... 查看详情

fastjson处理枚举

Fastjson这玩意儿不多说,Alibaba出品,出过几次严重的安全漏洞,但是依然很流行。这里写一下它怎么处理枚举。<!--https://mvnrepository.com/artifact/com.alibaba/fastjson--><dependency><groupId>com.alibaba</groupId><artifactI 查看详情

解决com.alibaba.fastjson.jsonexception:autotypeisnotsupport异常处理(代码片段)

最近在使用spring-data-redis时,使用fastjson的序列化方式GenericFastJsonRedisSerializer可以正常序列化,但在反序列化时发生了如下异常com.alibaba.fastjson.JSONException:autoTypeisnotsupport.com.hongshu.groovy.dto.Account。 仔细阅读了f 查看详情

fastjson

packagecom.hanqi.test;importjava.util.ArrayList;importjava.util.Date;importjava.util.List;importorg.json.JSONException;importcom.alibaba.fastjson.JSONArray;importcom.alibaba.fastjson.JSONObject;public 查看详情