递归将树转化成json字符串

来源:互联网 发布:mac五国循环重启 编辑:程序博客网 时间:2024/05/22 10:47

Tree.java:

package tree;import java.util.ArrayList;import java.util.List;class Node {private int data;private Node parent;private List<Node> children = new ArrayList<Node>();private Node rightSibling;public Node(int data) {this.data = data;}public int getData() {return data;}public void setData(int data) {this.data = data;}public Node getParent() {return parent;}public void setParent(Node parent) {this.parent = parent;}public List<Node> getChildren() {return children;}public void setChildren(List<Node> children) {this.children = children;}public Node getRightSibling() {return rightSibling;}public void setRightSibling(Node rightSibling) {this.rightSibling = rightSibling;}}public class Tree {private Node root;private StringBuffer buffer = new StringBuffer();public void init(Node root) {this.root = root;}public Node getRoot() {return this.root;}public void printTree() {convert(this.root);System.out.println(buffer.toString());}private void convert(Node node) {buffer.append("{\"data\":" + node.getData());if(node.getChildren().size() == 0) {buffer.append(",\"children\":null}");return;}else {buffer.append(", \"children\":[");for(Node n : node.getChildren()) {convert(n);buffer.append(",");}buffer = buffer.deleteCharAt(buffer.lastIndexOf(","));buffer.append("]}");}}}


TreeMain.java:

package tree;import java.util.List;public class TreeMain {public static void main(String[] args) {Node root = new Node(10);root.setData(10);Node n1 = new Node(1);Node n2 = new Node(2);Node n3 = new Node(3);n1.setParent(root);n2.setParent(root);n3.setParent(root);List<Node> list = root.getChildren();list.add(n1);list.add(n2);list.add(n3);root.setChildren(list);n1.setRightSibling(n2);n2.setRightSibling(n3);//======================================Node n4 = new Node(4);Node n5 = new Node(5);n4.setParent(n1);n5.setParent(n1);list = n1.getChildren();list.add(n4);list.add(n5);n1.setChildren(list);n4.setRightSibling(n5);//======================================Node n6 = new Node(6);Node n7 = new Node(7);n6.setParent(n2);n7.setParent(n2);list = n2.getChildren();list.add(n6);list.add(n7);n2.setChildren(list);n6.setRightSibling(n7);Tree tree = new Tree();tree.init(root);tree.printTree();System.out.println("\n" + root.getChildren().get(0).getRightSibling().getData());}}


运行结果:

{"data":10, "children":[{"data":1, "children":[{"data":4,"children":null},{"data":5,"children":null}]},{"data":2, "children":[{"data":6,"children":null},{"data":7,"children":null}]},{"data":3,"children":null}]}2


0 0
原创粉丝点击