将树形结构转成json格式的java代码
时间: 2024-02-16 07:35:47 浏览: 103
假设我们有如下的树形结构:
```
Root
|- Node1
| |- Node1.1
| |- Node1.2
| |- Node1.2.1
| |- Node1.2.2
|- Node2
|- Node2.1
|- Node2.2
```
我们可以定义一个Java类来表示树节点:
```java
public class TreeNode {
private String name;
private List<TreeNode> children;
public TreeNode(String name) {
this.name = name;
this.children = new ArrayList<>();
}
public void addChild(TreeNode child) {
this.children.add(child);
}
// getter and setter methods
}
```
然后,我们可以使用递归的方式将树形结构转成JSON格式的字符串:
```java
public static String treeToJson(TreeNode node) {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("\"name\": \"" + node.getName() + "\",");
sb.append("\"children\": [");
for (int i = 0; i < node.getChildren().size(); i++) {
TreeNode child = node.getChildren().get(i);
sb.append(treeToJson(child));
if (i < node.getChildren().size() - 1) {
sb.append(",");
}
}
sb.append("]");
sb.append("}");
return sb.toString();
}
```
最后,我们可以使用以下代码来测试:
```java
public static void main(String[] args) {
TreeNode root = new TreeNode("Root");
TreeNode node1 = new TreeNode("Node1");
TreeNode node11 = new TreeNode("Node1.1");
TreeNode node12 = new TreeNode("Node1.2");
TreeNode node121 = new TreeNode("Node1.2.1");
TreeNode node122 = new TreeNode("Node1.2.2");
node1.addChild(node11);
node1.addChild(node12);
node12.addChild(node121);
node12.addChild(node122);
TreeNode node2 = new TreeNode("Node2");
TreeNode node21 = new TreeNode("Node2.1");
TreeNode node22 = new TreeNode("Node2.2");
node2.addChild(node21);
node2.addChild(node22);
root.addChild(node1);
root.addChild(node2);
String json = treeToJson(root);
System.out.println(json);
}
```
输出结果为:
```
{
"name": "Root",
"children": [
{
"name": "Node1",
"children": [
{
"name": "Node1.1",
"children": []
},
{
"name": "Node1.2",
"children": [
{
"name": "Node1.2.1",
"children": []
},
{
"name": "Node1.2.2",
"children": []
}
]
}
]
},
{
"name": "Node2",
"children": [
{
"name": "Node2.1",
"children": []
},
{
"name": "Node2.2",
"children": []
}
]
}
]
}
```
阅读全文