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数据十分便利,后续再记录更多的使用技巧。

相关推荐
薛之谦_3 小时前
JAVA 多线程编程:从基础原理到实战应用
java·开发语言
LMT_Lanmantech3 小时前
Creo许可降本增效:不增购,也能让现有许可发挥更大价值
java·大数据·开发语言
Shaoshing3 小时前
Serializable
java
wuminyu3 小时前
ZGC染色指针在虚拟线程stackChunkOop上的并发屏障全景分析
java·linux·c语言·jvm·c++
蜗牛互联网3 小时前
Python Agent 工具调用:审批令牌、参数白名单和累计预算
java·开发语言·人工智能·windows·后端·python
哦虎!3 小时前
【JavaEE】网络编程套接字
java
Wang's Blog3 小时前
Java 项目实战: 交友项目 - SpringCloud 整合 Dubbo 的方案概述
java·spring cloud·交友
imDwAaY3 小时前
程序里的地址是真实内存地址吗?从虚拟内存到地址转换
java·linux·服务器
秋饼4 小时前
Claude Haiku 5.5 + Spring AI 2.0 企业级低成本高并发 AI Agent 实战:子智能体分工、成本熔断与百万上下文落地
java·ai·技术分享·后端开发
xuxigifxfh4 小时前
牛客:BISHI8 大整数哈希
java·算法·哈希算法