工具類
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
/**
- Map listToTree
- <p>方法說明<p>
- 將JSONArray數(shù)組轉(zhuǎn)為樹狀結(jié)構(gòu)
- @param arr 需要轉(zhuǎn)化的數(shù)據(jù)
- @param id 數(shù)據(jù)唯一的標(biāo)識鍵值
- @param pid 父id唯一標(biāo)識鍵值
- @param child 子節(jié)點鍵值
- @return JSONArray
*/
public static JSONArray listToTree(JSONArray arr, String id, String pid, String child){
JSONArray r = new JSONArray();
JSONObject hash = new JSONObject();
//將數(shù)組轉(zhuǎn)為Object的形式,key為數(shù)組中的id
for(int i=0;i<arr.size();i++){
JSONObject json = (JSONObject) arr.get(i);
hash.put(json.getString(id), json);
}
//遍歷結(jié)果集
for(int j=0;j<arr.size();j++){
//單條記錄
JSONObject aVal = (JSONObject) arr.get(j);
//解決key為空的問題(數(shù)據(jù)庫中父節(jié)點列為空)
//判斷JSONObject是否存在這個key值
if(!aVal.containsKey(pid)){
aVal.put(pid,"000");
}
//在hash中取出key為單條記錄中pid的值
JSONObject hashVP = (JSONObject) hash.get(aVal.get(pid).toString());
//如果記錄的pid存在身坐,則說明它有父節(jié)點茵乱,將她添加到孩子節(jié)點的集合中
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;
}
使用方法
List<Map<String,Object>> data = new ArrayList<>();
Map<String,Object> map = new HashMap<>();
map.put("id",1);
map.put("pid",0);
map.put("name","甘肅省");
data.add(map);
Map<String,Object> map2 = new HashMap<>();
map2.put("id",2);
map2.put("pid",1);
map2.put("name","天水市");
data.add(map2);
Map<String,Object> map3 = new HashMap<>();
map3.put("id",3);
map3.put("pid",2);
map3.put("name","秦州區(qū)");
data.add(map3);
Map<String,Object> map4 = new HashMap<>();
map4.put("id",4);
map4.put("pid",0);
map4.put("name","北京市");
data.add(map4);
Map<String,Object> map5 = new HashMap<>();
map5.put("id",5);
map5.put("pid",4);
map5.put("name","昌平區(qū)");
data.add(map5);
//////////////////////////////////////////////////////////////唯一id:id,父節(jié)點ID:pid则北,第三個是生成的子節(jié)點的名字隨便寫
//父節(jié)點ID在數(shù)據(jù)庫中不能為null可以為‘’
JSONArray result = CopyUtils.listToTree(JSONArray.parseArray(JSON.toJSONString(data)),"id","pid","aefsedfv");
結(jié)果集
原始數(shù)據(jù)
[
{
"name":"甘肅省",
"pid":0,
"id":1
},
{
"name":"天水市",
"pid":1,
"id":2
},
{
"name":"秦州區(qū)",
"pid":2,
"id":3
},
{
"name":"北京市",
"pid":0,
"id":4
},
{
"name":"昌平區(qū)",
"pid":4,
"id":5
}
]
結(jié)果集
[
{
"children":[
{
"children":[
{
"name":"秦州區(qū)",
"pid":2,
"id":3
}
],
"name":"天水市",
"pid":1,
"id":2
}
],
"name":"甘肅省",
"pid":0,
"id":1
},
{
"children":[
{
"name":"昌平區(qū)",
"pid":4,
"id":5
}
],
"name":"北京市",
"pid":0,
"id":4
}
]