You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中使用Jayway JsonPath获取查询节点的Json路径

实现方法

Jayway JsonPath本身提供了获取匹配节点精确路径的能力,你可以通过PathRef类来同时获取每个节点的具体路径和对应值,具体实现如下:

核心思路

利用Jayway的PathRef封装类,它会为每个匹配的JSON节点保存精确的带索引路径(比如$.people[0].research[0].years[0].year)和对应的值,只需将查询结果指定为List<PathRef>即可。

代码示例

import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.PathRef;
import com.jayway.jsonpath.ReadContext;
import java.util.List;

public class JsonPathPathDemo {
    public static void main(String[] args) {
        // 示例JSON数据
        String json = "{\"people\":[{\"research\":[{\"years\":[{\"year\":2020},{\"year\":2021}]}]}, {\"research\":[{\"years\":[{\"year\":2022}]}]}]}";
        
        // 解析JSON获取上下文
        ReadContext ctx = JsonPath.parse(json);
        
        // 查询并获取包含路径和值的PathRef列表
        List<PathRef> pathRefs = ctx.read("$.people[*].research[*].years[*].year", List.class);
        
        // 遍历输出每个节点的路径和值
        for (PathRef ref : pathRefs) {
            // 原始路径格式为$['people'][0]['research'][0]['years'][0]['year']
            String rawPath = ref.getPath();
            // 转换为点号加索引的格式
            String formattedPath = rawPath.replace("['", ".").replace("']", "");
            Object yearValue = ref.getValue();
            
            System.out.printf("路径: %s,值: %s%n", formattedPath, yearValue);
        }
    }
}

输出结果

运行代码后会输出:

路径: $.people[0].research[0].years[0].year,值: 2020
路径: $.people[0].research[0].years[1].year,值: 2021
路径: $.people[1].research[0].years[0].year,值: 2022

注意事项

  • 确保你的Jayway JsonPath版本在2.4.0及以上,PathRef特性在该版本后稳定支持
  • 无需额外配置,直接指定返回类型为List<PathRef>即可触发路径追踪

内容的提问来源于stack exchange,提问作者Thorsten

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 07:30:11