Java的JSONPath(fastjson)使用总结

背景

最近使用json实现复杂业务配置, 因为功能需要解析读取json的中节点数据。如果使用循环或者stream处理,可以实现,但是都过于麻烦。在想能否使用更简单json读取方式,正好发现fastjson支持该功能,本文做一个记录

案例说明

示例1使用fastjson实现,依赖如下

xml 复制代码
           <!--alibaba.json和依赖包-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.79</version>
            </dependency>

为了对比写法便捷性,示例2也提供jackson的部分实现方式。

示例1. fastjson实现json指定节点按条件过滤提取数据

使用 JSONPath.eval 来筛选 JSON 数据中符合特定条件的元素。以下是使用 eval 方法提取 author 等于 "Nigel Rees" 的那条记录的示例代码:

java 复制代码
public class JSONPathExample {
    public static void main(String[] args) {
        String json = "{\n" +
                "  \"store\": {\n" +
                "    \"book\": [\n" +
                "      { \"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95 },\n" +
                "      { \"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99 },\n" +
                "      { \"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"price\": 8.99 },\n" +
                "      { \"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"price\": 22.99 }\n" +
                "    ],\n" +
                "    \"bicycle\": {\n" +
                "      \"color\": \"red\",\n" +
                "      \"price\": 19.95\n" +
                "    }\n" +
                "  }\n" +
                "}";

        JSONObject jsonObject = JSON.parseObject(json);
        JSONArray result = (JSONArray) JSONPath.eval(jsonObject, "$.store.book[?(@.author == 'Nigel Rees')]");

        for (Object book : result) {
            System.out.println(book);
        }
    }
}

运行结果如下,符合预期。而且代码非常简洁。

复制代码
{"author":"Nigel Rees","price":8.95,"category":"reference","title":"Sayings of the Century"}

示例2. jackson实现json指定节点按条件过滤提取数据

jackson 不支持直接使用 JSONPath 表达式,但可以通过结合 Jackson 和 Java 流操作实现类似的功能。以下是一个使用 Jackson 过滤 JSON 数据中 type 为 'AggregateRoot' 的节点的示例:

java 复制代码
public class JacksonExample {
    public static void main(String[] args) throws IOException {
        String json = "{\n" +
                "  \"classDiagram\": {\n" +
                "    \"nodes\": [\n" +
                "      { \"id\": \"1\", \"type\": \"AggregateRoot\", \"name\": \"Node1\" },\n" +
                "      { \"id\": \"2\", \"type\": \"Entity\", \"name\": \"Node2\" },\n" +
                "      { \"id\": \"3\", \"type\": \"AggregateRoot\", \"name\": \"Node3\" },\n" +
                "      { \"id\": \"4\", \"type\": \"ValueObject\", \"name\": \"Node4\" }\n" +
                "    ]\n" +
                "  }\n" +
                "}";

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(json);
        JsonNode nodesNode = rootNode.path("classDiagram").path("nodes");

        List<Map<String, Object>> nodes = new ArrayList<>();

        if (nodesNode.isArray()) {
            nodes = StreamSupport.stream(nodesNode.spliterator(), false)
                    .filter(node -> "AggregateRoot".equals(node.path("type").asText()))
                    .map(node -> objectMapper.convertValue(node, Map.class))
                    .collect(Collectors.toList());
        }

        for (Map<String, Object> node : nodes) {
            System.out.println(node);
        }
    }
}

总结

fastjson的JSONPath.eval方法对于快速解析json数据十分便利,后续再记录更多的使用技巧。

相关推荐
2601_94980959几秒前
flutter_for_openharmony家庭相册app实战+我的Tab实现
java·javascript·flutter
vx_BS8133030 分钟前
【直接可用源码免费送】计算机毕业设计精选项目03574基于Python的网上商城管理系统设计与实现:Java/PHP/Python/C#小程序、单片机、成品+文档源码支持定制
java·python·课程设计
2601_9498683630 分钟前
Flutter for OpenHarmony 电子合同签署App实战 - 已签合同实现
java·开发语言·flutter
达文汐1 小时前
【困难】力扣算法题解析LeetCode332:重新安排行程
java·数据结构·经验分享·算法·leetcode·力扣
培风图南以星河揽胜1 小时前
Java版LeetCode热题100之零钱兑换:动态规划经典问题深度解析
java·leetcode·动态规划
启山智软1 小时前
【中大企业选择源码部署商城系统】
java·spring·商城开发
我真的是大笨蛋1 小时前
深度解析InnoDB如何保障Buffer与磁盘数据一致性
java·数据库·sql·mysql·性能优化
怪兽源码2 小时前
基于SpringBoot的选课调查系统
java·spring boot·后端·选课调查系统
恒悦sunsite2 小时前
Redis之配置只读账号
java·redis·bootstrap
梦里小白龙2 小时前
java 通过Minio上传文件
java·开发语言