JAVA 转换 树结构数据
2024-08-29 02:28:35
JAVA 转换 树结构数据
第一步:引入fastjson
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
第二步:用到了工具内的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);
}
}
最新文章
- 面试中常用的__proto__,prototype和原型链,你都了解了吗?
- Jenkins的系统设置
- bootstrap加深
- DataTable.Compute()用法
- C++_Eigen函数库用法笔记——Block Operations
- web双机热备添加心跳检测ip的时候填了网关导致外网ip不能上网
- 跨平台c++ Coroutine,仿unity3d实现
- Jquery实现文本框获取焦点清空内容,失去焦点重新获得内容的公共函数
- 在 windows 上面安装 tensorflow
- CentOS 配置httpd使局域网能够正常訪问
- Quartz(GUI)图形界面程序----Quartz Web
- spring配置文件一般结构
- Spring之旅第二篇-Spring IOC概念及原理分析
- C# net request payload形式发送post请求
- JS数字转中文
- C语言malloc函数为一维,二维,三维数组分配空间
- mysql 5.7 ERROR 1820 (HY000):
- CF11D A Simple Task 状压DP
- Web上传文件的原理及实现
- rsync未授权访问漏洞利用