在開發中,我們經常需要在前端將數據以樹形結構展現出來。而構造這樣的樹結構是一件很麻煩的事情。在Java中,通過構造JSON樹,我們可以很方便地在前端展現出樹形結構數據。下面就介紹一下如何構造JSON樹。
public static JsonNode buildTree(List<Node> nodeList) { Map<String, Object> treeMap = nodeList.get(0).getAttributes(); treeMap.put("children", new ArrayList<>()); for (int i = 1; i < nodeList.size(); i++) { Node node = nodeList.get(i); recursivelyBuildTree(node, treeMap); } ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writeValueAsString(treeMap); return mapper.readTree(jsonString); } private static void recursivelyBuildTree(Node node, Map<String, Object> parentMap) { String parentId = node.getParentId(); String currentId = node.getId(); Map<String, Object> currentMap = new HashMap<>(node.getAttributes()); currentMap.put("children", new ArrayList<>()); if (parentMap.containsKey(currentId)) { ((List) parentMap.get(currentId)).add(currentMap); } else { recursivelyAddNode(parentId, currentMap, parentMap); } } private static void recursivelyAddNode(String parentId, Map<String, Object> currentMap, Map<String, Object> parentMap) { if (parentMap.containsKey(parentId)) { List<Map<String, Object>> childrenList = (List<Map<String, Object>>) parentMap.get(parentId); childrenList.add(currentMap); } else { Node parentNode = getNodeById(parentId, nodeList); Map<String, Object> parentNodeMap = new HashMap<>(parentNode.getAttributes()); parentNodeMap.put("children", new ArrayList<>()); recursivelyAddNode(parentNode.getParentId(), parentNodeMap, parentMap); ((List) parentNodeMap.get("children")).add(currentMap); parentMap.put(parentId, parentNodeMap); } } private static Node getNodeById(String nodeId, List<Node> nodeList) { for (Node node : nodeList) { if (node.getId().equals(nodeId)) { return node; } } return null; }
在這段代碼中,我們構造了一個包含“children”鍵值對的樹形結構。然后使用遞歸的方式依次添加每個節點,并將結果以JSON字符串的形式返回。最終,將JSON字符串解析為JsonNode對象,返回給前端。