欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

JAVA如何转换树结构数据代码实例

时间:2021-07-09 08:27:44|栏目:JAVA代码|点击:

在实战开发中经常有需要处理树形菜单、树形目录等等等业务需求。而对于这种产品,在设计数据库时也建议使用id<----->parentId的结构来做。但是最终前端显示多用hightChart或者Echart插件来实现。所以在给前端数据时,最好的做法就是把数据库结构话的数据处理成treeJson格式。

第一步:引入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);
    }
  }

上一篇:Java中的StringBuilder性能测试

栏    目:JAVA代码

下一篇:java实现mongodb的数据库连接池

本文标题:JAVA如何转换树结构数据代码实例

本文地址:http://www.codeinn.net/misctech/154871.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有