首先定义一个组织架构树节点对象Department,对象属性包括id、parentId、name和children:
@Data
public class Department {
private long id;
private long parentId;
private String name;
private List<Department> children = new ArrayList<>();
}
在构建组织架构树的过程中,将每个树节点转换为Department对象:
public static String buildDeptTreeJson(List<Department> deptList, long rootId) {
// 从 deptList 中获取根节点
Optional<Department> root = deptList.stream().filter(dept -> dept.getId() == rootId).findAny();
if (!root.isPresent()) {
return null;
}
// 递归构建树形结构
return buildSubDeptTreeJson(root.get(), deptList).toString();
}
private static JsonObject buildSubDeptTreeJson(Department deptNode, List<Department> deptList) {
JsonObject nodeJson = new JsonObject();
nodeJson.addProperty("id", deptNode.getId());
nodeJson.addProperty("name", deptNode.getName());
// 遍历子节点
if (!deptNode.getChildren().isEmpty()) {
JsonArray childrenArray = new JsonArray();
deptNode.getChildren().forEach(childNode -> {
JsonObject childJson = buildSubDeptTreeJson(childNode, deptList);
childrenArray.add(childJson);
});
nodeJson.add("children", childrenArray);
}
return nodeJson;
}
这样就可以实现一个组织机构树的 JSON 格式对象的组装