forked from isomd/PromptoLab
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQaTreeSerializeUtil.java
More file actions
48 lines (35 loc) · 1.38 KB
/
QaTreeSerializeUtil.java
File metadata and controls
48 lines (35 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package io.github.timemachinelab.util;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.github.timemachinelab.core.qatree.QaTree;
import io.github.timemachinelab.core.qatree.QaTreeNode;
import io.github.timemachinelab.core.serializable.JsonNode;
import java.util.ArrayList;
import java.util.List;
public class QaTreeSerializeUtil {
public static String serialize(QaTree t) throws JsonProcessingException {
if (t == null || t.getRoot() == null) {
return "[]";
}
List<JsonNode> result = new ArrayList<>();
firstOrderTraversal(t.getRoot(), null, result);
return JSONObject.toJSONString(result);
}
private static void firstOrderTraversal(QaTreeNode node, String parentId, List<JsonNode> result) throws JsonProcessingException {
if (node == null) {
return;
}
// 获取子节点列表
List<QaTreeNode> children = new ArrayList<>();
if (node.getChildren() != null) {
children.addAll(node.getChildren().values());
}
// 访问当前节点
JsonNode jsonNode = JsonNode.Convert2JsonNode(node, parentId);
result.add(jsonNode);
// 先序遍历
for (QaTreeNode child : children) {
firstOrderTraversal(child, node.getId(), result);
}
}
}