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);
}
}

赵小胖个人博客

最新文章

  1. 面试中常用的__proto__,prototype和原型链,你都了解了吗?
  2. Jenkins的系统设置
  3. bootstrap加深
  4. DataTable.Compute()用法
  5. C++_Eigen函数库用法笔记——Block Operations
  6. web双机热备添加心跳检测ip的时候填了网关导致外网ip不能上网
  7. 跨平台c++ Coroutine,仿unity3d实现
  8. Jquery实现文本框获取焦点清空内容,失去焦点重新获得内容的公共函数
  9. 在 windows 上面安装 tensorflow
  10. CentOS 配置httpd使局域网能够正常訪问
  11. Quartz(GUI)图形界面程序----Quartz Web
  12. spring配置文件一般结构
  13. Spring之旅第二篇-Spring IOC概念及原理分析
  14. C# net request payload形式发送post请求
  15. JS数字转中文
  16. C语言malloc函数为一维,二维,三维数组分配空间
  17. mysql 5.7 ERROR 1820 (HY000):
  18. CF11D A Simple Task 状压DP
  19. Web上传文件的原理及实现
  20. rsync未授权访问漏洞利用

热门文章

  1. 微信发送朋友圈URL JSAPI事件demo
  2. iPhoneSE2要在印度独家生产真得没戏?
  3. [洛谷P3403] 跳楼机
  4. CPU网卡亲和绑定
  5. [Gem] AASM 狀態機
  6. 关于线上bug
  7. Atom配置(VIM党) &middot; iuunhao
  8. 为何滴滴会走Uber之路,研发无人驾驶?
  9. (转载)SVN使用说明
  10. 牛奶别乱喝6种最好最差牛奶PK