list轉json tree的工具類
package com.glodon.safety.contingency.job; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.util.*; /** * @Description 通用的list轉json tree的工具類 * @Author songwp * @Date 2022/12/30 12:59 * @Version 1.0.0 **/ public class CommonTreeUtil { /** - listToTree - <p>方法說明<p> - 將JSONArray數組轉為樹狀結構 - @param arr 需要轉化的數據 - @param id 數據唯一的標識鍵值 - @param pid 父id唯一標識鍵值 - @param child 子節點鍵值 - @return JSONArray */ public static JSONArray listToTree(JSONArray arr, String id, String pid, String child){ JSONArray r = new JSONArray(); JSONObject hash = new JSONObject(); //將數組轉為Object的形式,key為數組中的id for(int i=0;i<arr.size();i++){ JSONObject json = (JSONObject) arr.get(i); hash.put(json.getString(id), json); } //遍歷結果集 for(int j=0;j<arr.size();j++){ //單條記錄 JSONObject aVal = (JSONObject) arr.get(j); //在hash中取出key為單條記錄中pid的值 JSONObject hashVP = (JSONObject) hash.get(aVal.get(pid).toString()); //如果記錄的pid存在,則說明它有父節點,將她添加到孩子節點的集合中 if(hashVP!=null){ //檢查是否有child屬性 if(hashVP.get(child)!=null){ JSONArray ch = (JSONArray) hashVP.get(child); ch.add(aVal); hashVP.put(child, ch); }else{ JSONArray ch = new JSONArray(); ch.add(aVal); hashVP.put(child, ch); } }else{ r.add(aVal); } } return r; } public static void main(String[] args) { Map map = new HashMap(); map.put("id","1"); map.put("parentId","0"); map.put("name","陜西省"); Map map1 = new HashMap(); map1.put("id","2"); map1.put("parentId","1"); map1.put("name","西安市"); Map map2 = new HashMap(); map2.put("id","3"); map2.put("parentId","2"); map2.put("name","雁塔區"); Map map3 = new HashMap(); map3.put("id","4"); map3.put("parentId","1"); map3.put("name","咸陽市"); List<Map> mapList = Arrays.asList(map, map1, map2, map3); JSONArray result = CommonTreeUtil.listToTree(JSONArray.parseArray(JSON.toJSONString(mapList)),"id","parentId","children"); System.out.println(result); } }
控制臺輸出:
[ { "children":[ { "children":[ { "name":"雁塔區", "id":"3", "parentId":"2" } ], "name":"西安市", "id":"2", "parentId":"1" }, { "name":"咸陽市", "id":"4", "parentId":"1" } ], "name":"陜西省", "id":"1", "parentId":"0" } ]
方法拓展
public List<DictTypeVO> getTree() { List<DictTypeVO> dictTypeVOS = DictTypeDomainService().findAllList(); return buildTreeUseList(dictTypeVOS, 0); } /** * 使用遞歸構建樹結構-使用foreach轉換 * @param treeList * @param id * @return */ public static List<DictTypeVO> buildTreeUseList(List<DictTypeVO> treeList,long id ) { //收集傳遞的集合中父id相同的TreeNode List<DictTypeVO> children = new ArrayList<>(); for (DictTypeVO treeNode : treeList) { //判斷該節點的父id,是否與傳入的父id相同,相同則遞歸設置其孩子節點,并將該節點放入children集合中 if(treeNode.getParentId() == id){ //遞歸設置其孩子節點 treeNode.setChildren(buildTreeUseList(treeList, treeNode.getId())); //放入children集合 children.add(treeNode); } } return children; }
古今成大事者,不唯有超世之才,必有堅韌不拔之志!

浙公網安備 33010602011771號