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

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

铜陵网站建设公司成都创新互联公司,铜陵网站设计制作,有大型网站制作公司丰富经验。已为铜陵上1000+提供企业网站建设服务。企业网站搭建\外贸网站建设要多少钱,请找那个售后服务好的铜陵做网站的公司定做!

第一步:引入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如何转换树结构数据代码实例
文章起源:https://www.cdcxhl.com/article0/gshsoo.html

成都网站建设公司_创新互联,为您提供App开发软件开发响应式网站网站收录品牌网站制作手机网站建设

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

h5响应式网站建设