从数据库查出一堆集合数据之后,数据是按照一二三级这种规律,在这里做一个树状排序,为了方便大家优化了下代码,直接复制粘贴就可以使用
数据需要id,pid,name即可支持
首先引入net.sf.JSON,个人比较习惯用这个,读者随意
/**
*parentId为当前List最上层父id
*idKey为实体类对象中id键名
*parentKey为实体类对象中id的键名
*childName为返回数据子列表的命名
*/
public class treeObjectList{
publlic static JSONArray forObjectToTreeMap(List<?> treeList,Long parentId,String idKey,String parentIdKey,String childName){
JSONArray childMenu = new JSONArray();
for(Object object : treeList){
JSONObject jsonMenu = JSONObject.fromObject(object);
Long menuId = jsonMenu.getLong(idKey);
Long pid = jsonMenu.getLong(parentIdKey);
if(parentId==pid){
JSONArray array = forObjectToTreeMap(treeList,menuId);
jsonMenu.put(childName,array);
childMenu.add(jsonMenu);
}
版权声明:本文为MengDiL_yl原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。