使用场景
很多时候我们调用上游接口拿到的返回值是json字符串,如果不存在上游共享的公用返回值类,那么下游可能会直接使用JsonObject之类的动态对象类承接这份数据。这时候对于很深的的属性取值是非常复杂的
我们大概会这样写
上面这种写法是非常恶心的,尤其是在层次比较多的时候,如果使用jsonPath一切就变得简单了
哪些框架支持jsonPath?
fastjson是有jsonPath支持的,redis的json类型,mysql的json类型也都有对jsonPath的支持
hutools 的ison格式化也是对jsonPath有支持的,支持程度不如fastjson
jayway 也是对jsonPath有支持的,但是它默认处理方案是路径不存在报错,不好用
fastJson对jsonPath的支持
可以取值的数据源支持json字符串,JSONObject对象,支持普通java对象
可以指定返回值数据类型
可以静态方法获取数据
它的内部实现是通过多层Segment去一层一层的去取数据
compile是有模版缓存比直接new JsonPath效率高。
read方法底层也用的evel方法
一些常见的方法
取值
删除,修改,取size,得到keys
判断值和path是否存在
输出path
对数组追加值
hutool对jsonPath的支持
jayway对jsonPath的支持
jayway是spring-boot-starter自带的jsonPath工具
使用例子