用java实现 递归查询归多级树形结构数据的代码,并以json格式返回
时间: 2024-05-12 20:19:52 浏览: 11
以下是一个递归查询多级树形结构数据并以JSON格式返回的Java代码示例:
```java
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
public class RecursiveTreeExample {
public static void main(String[] args) {
List<Node> treeList = new ArrayList<>();
treeList.add(new Node("1", null, "Root"));
treeList.add(new Node("2", "1", "Node 1-1"));
treeList.add(new Node("3", "1", "Node 1-2"));
treeList.add(new Node("4", "2", "Node 2-1"));
treeList.add(new Node("5", "2", "Node 2-2"));
treeList.add(new Node("6", "4", "Node 3-1"));
treeList.add(new Node("7", "4", "Node 3-2"));
String json = JSON.toJSONString(buildTree("1", treeList));
System.out.println(json);
}
public static List<Node> buildTree(String parentId, List<Node> nodeList) {
List<Node> treeList = new ArrayList<>();
for (Node node : nodeList) {
if (parentId.equals(node.parentId)) {
List<Node> children = buildTree(node.id, nodeList);
if (!children.isEmpty()) {
node.children = children;
}
treeList.add(node);
}
}
return treeList;
}
static class Node {
String id;
String parentId;
String name;
List<Node> children;
public Node(String id, String parentId, String name) {
this.id = id;
this.parentId = parentId;
this.name = name;
this.children = new ArrayList<>();
}
}
}
```
在这个示例中,我们定义了一个Node类来表示多级树形结构中的节点,包括节点ID、父节点ID、节点名称和子节点列表。我们还定义了一个buildTree方法来递归地构建树形结构。该方法接受一个parentId和一个节点列表作为输入,并返回具有指定parentId的所有子节点的列表。如果一个节点有子节点,我们递归调用buildTree方法来构建其子树,并将其子节点列表设置为该节点的children属性。最后,我们使用FastJSON库将树形结构转换为JSON格式并输出到控制台。