获取json叶子节点的jsonPath

maven的pom文件

    <dependencies>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.31</version>
        </dependency>
    </dependencies>

实现代码

      public static  List<String> getListJson(JSONObject jsonObject) {
        // 获取到所有jsonpath后,获取所有的key
        List<String> jsonPaths = JSONPath.paths(jsonObject).keySet()
                .stream()
                .collect(Collectors.toList());
        //去掉根节点key
        List<String> parentNode = new ArrayList<>();
        //根节点key
        parentNode.add("/");
        //循环获取父节点key,只保留叶子节点
        for (int i = 0; i < jsonPaths.size(); i++) {
            if (jsonPaths.get(i).lastIndexOf("/") > 0) {
                parentNode.add(jsonPaths.get(i).substring(0, jsonPaths.get(i).lastIndexOf("/")));
            }
        }

        //remove父节点key
        for (String parentNodeJsonPath : parentNode) {
            jsonPaths.remove(parentNodeJsonPath);
        }

        List<String> jsonPathList = new ArrayList<>();
        Iterator<String> jsonPath = jsonPaths.iterator();
        //将/替换为点.
        while (jsonPath.hasNext()) {
            jsonPathList.add(jsonPath.next().replaceFirst("/", "").replaceAll("/", "."));
        }
        //排序
        Collections.sort(jsonPathList);
        return jsonPathList;
    }

    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        JSONPath.set(jsonObject,"data.person","个人");
        JSONPath.set(jsonObject,"data.student.age","20");
        JSONPath.set(jsonObject,"data.student.name","张三");

        List<String> listJsonPath = getListJson(jsonObject);
        for(String jsonPath:listJsonPath){
            System.out.println(jsonPath);
        }
    }

执行结果

data.person
data.student.age
data.student.name

扩展

1.可通过jsonpath去获取json的value
JSONPath.eval(jsonObject,“data.student.name”)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值