JAVA 转换 树结构数据

JAVA 转换 树结构数据

第一步:引入fastjson

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>${fastjson.version}</version>
</dependency>

第二步:用到了工具内的JSONPath

JSONPath使用教程

    /**
     * 树转换
     *
     * @param obj                  需要转换的对象
     * @param parentCodeFieldName  父标识字段名
     * @param parentCode           父标识值
     * @param currentCodeFieldName 当前标识字段名
     * @param childrenFiledName    子树的字段名
     * @param c                    需要转换的Class类型
     * @param <T>                  泛型
     * @return 返回List<T>
     */
    public static <T> List<T> tree(Object obj, String parentCodeFieldName, String parentCode, String currentCodeFieldName, String childrenFiledName, Class<T> c) {
        long t1 = System.currentTimeMillis();
        String jsonStr = JSON.toJSONString(obj);
        log.debug("树转换开始 >>>>>>>>>>>>>>>> {}", JSON.toJSONString(obj));
        //获取第一层级的数据
        JSONArray jsonArray = (JSONArray) JSONPath.read(jsonStr, "$[" + parentCodeFieldName + "=" + parentCode + "]");
        if (CollectionUtils.isEmpty(jsonArray)) {
            //为空的话直接返回空集合
            return Lists.newArrayList();
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String code = jsonObject.getString(currentCodeFieldName);
            treeChildren(jsonStr, jsonObject, parentCodeFieldName, code, currentCodeFieldName, childrenFiledName);
        }
        List<T> list = JSONArray.parseArray(jsonArray.toString(), c);
        log.debug("树转换结束, 转换时间: {} ms . >>>>>>>>>>>>>>>> {}", (System.currentTimeMillis() - t1), JSON.toJSONString(list));
        return list;
    }

    private static void treeChildren(String jsonStr, JSONObject currentJsonObj, String parentCodeFieldName, String parentCode, String currentCodeFieldName, String childrenFiledName) {
        JSONArray jsonArray = (JSONArray) JSONPath.read(jsonStr, "$[" + parentCodeFieldName + "=" + parentCode + "]");
        if (CollectionUtils.isEmpty(jsonArray)) {
            return;
        }
        currentJsonObj.put(childrenFiledName, jsonArray);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String code = jsonObject.getString(currentCodeFieldName);
            treeChildren(jsonStr, jsonObject, parentCodeFieldName, code, currentCodeFieldName, childrenFiledName);
        }
    }

赵小胖个人博客

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值