四)绘树
實測代碼:
import java.util.ArrayList; import java.util.List;import net.sf.json.JSONArray; import net.sf.json.JSONObject;import org.junit.Test;public class Digui {@Testpublic void drawTree() {List<Node> nodeList = new ArrayList<Node>();nodeList.add(new Node("0001", "null", "中國"));nodeList.add(new Node("0002", "0001", "河北"));nodeList.add(new Node("0003", "0001", "遼寧"));nodeList.add(new Node("0004", "0002", "石家莊"));nodeList.add(new Node("0005", "0003", "沈陽"));nodeList.add(new Node("0006", "null", "美國"));nodeList.add(new Node("0007", "0006", "紐約"));System.out.println(children("null", nodeList));}// 遞歸條件:1. 延伸 2.有盡頭public JSONArray children(String my, List<Node> nodes) {JSONArray myChildren = new JSONArray();for (Node node : nodes) {String id = node.getId();String pid = node.getPid();if (my.equals(pid)) {JSONObject myChild = new JSONObject();myChild.put("id", id);myChild.put("pid", pid);myChild.put("name", node.getName());JSONArray myChildChildren = children(id, nodes);if (myChildChildren.size() > 0)myChild.put("children", myChildChildren);myChildren.add(myChild);}}return myChildren;}}class Node {public Node(String id, String pid, String name) {this.id = id;this.pid = pid;this.name = name;}private String id;private String pid;private String name;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getPid() {return pid;}public void setPid(String pid) {this.pid = pid;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "Node [id=" + id + ", pid=" + pid + ", name=" + name + "]";} }?
打印結果:
[{"id":"0001","pid":null,"name":"中國","children":[{"id":"0002","pid":"0001","name":"河北","children":[{"id":"0004","pid":"0002","name":"石家莊"}]},{"id":"0003","pid":"0001","name":"遼寧","children":[{"id":"0005","pid":"0003","name":"沈陽"}]}]},{"id":"0006","pid":null,"name":"美國","children":[{"id":"0007","pid":"0006","name":"紐約"}]}]?
格式化結果:
[{"id": "0001","pid": null,"name": "中國","children": [{"id": "0002","pid": "0001","name": "河北","children": [{"id": "0004","pid": "0002","name": "石家莊"}]},{"id": "0003","pid": "0001","name": "遼寧","children": [{"id": "0005","pid": "0003","name": "沈陽"}]}]},{"id": "0006","pid": null,"name": "美國","children": [{"id": "0007","pid": "0006","name": "紐約"}]} ]?
實際項目應用見:SMSE
為 easyui-tree
轉載于:https://www.cnblogs.com/zno2/p/4866517.html
總結
- 上一篇: Python 爬虫1——爬虫简述
- 下一篇: EditText显示明文与密码