Actual code:
Importjava.util.ArrayList;Importjava.util.List;ImportNet.sf.json.JSONArray;ImportNet.sf.json.JSONObject;Importorg.junit.Test; Public classDigui {@Test Public voidDrawtree () {List<Node> nodeList =NewArraylist<node>(); Nodelist.add (NewNode ("0001", "null", "China")); Nodelist.add (NewNode ("0002", "0001", "Hebei")); Nodelist.add (NewNode ("0003", "0001", "Liaoning")); Nodelist.add (NewNode ("0004", "0002", "Shijiazhuang")); Nodelist.add (NewNode ("0005", "0003", "Shenyang")); Nodelist.add (NewNode ("0006", "null", "United States")); Nodelist.add (NewNode ("0007", "0006", "New York")); System.out.println (Children ("NULL", nodeList)); } //recursive conditions: 1. Extension 2. There's an end. PublicJsonarray Children (String my, list<node>nodes) {Jsonarray Mychildren=NewJsonarray (); for(Node node:nodes) {String ID=Node.getid (); String PID=Node.getpid (); if(My.equals (PID)) {Jsonobject MyChild=NewJsonobject (); 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); } } returnMychildren; }}classNode { PublicNode (string ID, string pid, string name) { This. ID =ID; This. PID =pid; This. Name =name; } PrivateString ID; PrivateString pid; PrivateString name; PublicString getId () {returnID; } Public voidsetId (String id) { This. ID =ID; } PublicString getpid () {returnpid; } Public voidsetpid (String pid) { This. PID =pid; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } @Override PublicString toString () {return"Node [id=" + ID + ", pid=" + pid + ", name=" + name + "]"; }}
Printing results:
[{"id": "0001", "pid": null, "name": "China", "children": [{"id": "0002", "pid": "0001", "name": "Hebei", "children": [{"id": "0004 "," pid ":" 0002 "," name ":" Shijiazhuang "}]},{" id ":" 0003 "," pid ":" 0001 "," name ":" Liaoning "," children ": [{" id ":" 0005 "," pid ":" 0003 "," Name ":" Shenyang "}]}]},{" id ":" 0006 "," pid ": null," name ":" United States "," children ": [{" id ":" 0007 "," pid ":" 0006 "," Name ":" New York "}]}]
Formatting results:
[ { "ID":"0001", "PID":NULL, "name":"China", "Children": [ { "ID":"0002", "PID":"0001", "name":"Hebei", "Children": [ { "ID":"0004", "PID":"0002", "name":"Shijiazhuang" } ] }, { "ID":"0003", "PID":"0001", "name":"Liaoning", "Children": [ { "ID":"0005", "PID":"0003", "name":"Shenyang" } ] } ] }, { "ID":"0006", "PID":NULL, "name":"United States", "Children": [ { "ID":"0007", "PID":"0006", "name":"New York" } ] }]
Actual Project application See:Smse
To Easyui-tree
Four) draw a tree