在Java中,JSON是一種常用的數(shù)據(jù)格式,而將它轉(zhuǎn)換成樹形結(jié)構(gòu)對(duì)于數(shù)據(jù)處理來(lái)說(shuō)非常有用。JSON轉(zhuǎn)樹形結(jié)構(gòu)就是將JSON對(duì)象轉(zhuǎn)換成一棵樹,每個(gè)屬性對(duì)應(yīng)樹的一個(gè)節(jié)點(diǎn),它的值對(duì)應(yīng)節(jié)點(diǎn)的值,而數(shù)組則可以轉(zhuǎn)換成一個(gè)節(jié)點(diǎn)的子樹。
public class JsonToTree { public static void main(String[] args) { String json = "{\"name\":\"John\", \"age\":30, \"cars\":[{\"name\":\"Ford\"},{\"name\":\"BMW\"}]}"; TreeNode root = jsonToTree(json); System.out.println(root); } private static TreeNode jsonToTree(String json) { JsonParser parser = new JsonParser(); JsonElement element = parser.parse(json); return jsonElementToTreeNode(element); } private static TreeNode jsonElementToTreeNode(JsonElement element) { if (element.isJsonPrimitive()) { return new TreeNode(element.getAsString()); } else if (element.isJsonArray()) { JsonArray array = element.getAsJsonArray(); TreeNode node = new TreeNode("[]"); for (JsonElement el : array) { node.addChild(jsonElementToTreeNode(el)); } return node; } else if (element.isJsonObject()) { JsonObject obj = element.getAsJsonObject(); TreeNode node = new TreeNode("{}"); for (Map.Entryentry : obj.entrySet()) { node.addChild(new TreeNode(entry.getKey(), jsonElementToTreeNode(entry.getValue()))); } return node; } return null; } } class TreeNode { private String key; private String value; private List children; public TreeNode(String key) { this.key = key; children = new ArrayList<>(); } public TreeNode(String key, TreeNode child) { this.key = key; children = new ArrayList<>(); children.add(child); } public TreeNode(String key, List children) { this.key = key; this.children = children; } public void addChild(TreeNode child) { children.add(child); } public String toString() { String result = key + "\n"; for (TreeNode child : children) { result += "|-- " + child.toString().replaceAll("\n", "\n ") + "\n"; } return result; } }
該代碼使用了Google Gson庫(kù)以及JsonParser類,通過(guò)遞歸遍歷解析JSON對(duì)象并使用自定義的TreeNode類構(gòu)建樹。調(diào)用jsonToTree()方法以傳遞JSON字符串作為參數(shù),并返回根節(jié)點(diǎn)。TreeNode類表示樹中的每個(gè)節(jié)點(diǎn),包含其鍵值以及可選的子節(jié)點(diǎn)List。
通過(guò)在控制臺(tái)上打印該根節(jié)點(diǎn),我們可以看到JSON數(shù)據(jù)的樹形結(jié)構(gòu)。