当前端需要返回如下结构的json时候:
{
"success":true,
"code":20000,
"message":"成功",
"data":{
"list":[
Object{...},
Object{...},
{
"id":"1521703425235382274",
"label":"数据库",
"children":[
{
"id":"1521703425302491138",
"label":"mysql",
"children":[
],
"pid":"1521703425235382274"
}
],
"pid":"0"
},
Object{...}
]
}
}
2种情况
- 只有一颗树结构:
例如一个系统有多个子系统
@Test
public void test03() {
HashMap<Integer, TestDemo> map = new HashMap<>();
List<TestDemo> list = new ArrayList<TestDemo>();
list.add(new TestDemo(1, "1",0, new ArrayList<TestDemo>()));
list.add(new TestDemo(2, "2", 1,new ArrayList<TestDemo>()));
list.add(new TestDemo(3, "3", 2,new ArrayList<TestDemo>()));
list.add(new TestDemo(4, "4", 1,new ArrayList<TestDemo>()));
list.add(new TestDemo(5, "5", 4,new ArrayList<TestDemo>()));
list.add(new TestDemo(6, "6", 4,new ArrayList<TestDemo>()));
list.add(new TestDemo(9, "9", 2,new ArrayList<TestDemo>()));
list.add(new TestDemo(7, "7", 3,new ArrayList<TestDemo>()));
list.add(new TestDemo(8, "8", 3,new ArrayList<TestDemo>()));
for (TestDemo testDemo : list) {
map.put(testDemo.getKey(), testDemo);
}
TestDemo root = null;
for (TestDemo testDemo : list) {
if(testDemo.getPid() == 0){
root = testDemo;
continue;
}
map.get(testDemo.getPid()).getChildren().add(testDemo);
}
System.out.println(root);
实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TestDemo {
int key;
String name;
int pid;
List<TestDemo> children;
}
2.多颗树结构 例如多门学科为父根,每门学科有不同的章节
List<TestDemo> list = new ArrayList<TestDemo>();
list.add(new TestDemo(2, "2", 1,new ArrayList<TestDemo>()));
list.add(new TestDemo(3, "3", 2,new ArrayList<TestDemo>()));
list.add(new TestDemo(4, "4", 1,new ArrayList<TestDemo>()));
list.add(new TestDemo(5, "5", 4,new ArrayList<TestDemo>()));
list.add(new TestDemo(6, "6", 4,new ArrayList<TestDemo>()));
list.add(new TestDemo(1, "1",0, new ArrayList<TestDemo>()));
list.add(new TestDemo(9, "9", 2,new ArrayList<TestDemo>()));
list.add(new TestDemo(7, "7", 3,new ArrayList<TestDemo>()));
list.add(new TestDemo(8, "8", 3,new ArrayList<TestDemo>()));
list.add(new TestDemo(11, "11", 0,new ArrayList<TestDemo>()));
list.add(new TestDemo(12, "12", 11,new ArrayList<TestDemo>()));
list.add(new TestDemo(13, "13",11,new ArrayList<TestDemo>()));
以0有2棵树
增加 List roots = new ArrayList<>(); root = testDemo 改成 roots.add(testDemo);
其中的实体类中的list属性,个人建议new出来比较好。当后端查的数据和前端的数据不一致时,建议自己重新遍历生成一个vo对象包含初始化好list再去做父子关系构造
|