Obtain the json string of the tree type.
Public class TreeNode {
Private long nodeId;
Private String nodeName;
Private long fatherNodeId;
Public TreeNode (){
}
Public TreeNode (long nodeId, String nodeName, long fatherNodeId ){
This. nodeId = nodeId;
This. nodeName = nodeName;
This. fatherNodeId = fatherNodeId;
}
Public long getNodeId (){
Return nodeId;
}
Public void setNodeId (long nodeId ){
This. nodeId = nodeId;
}
Public String getNodeName (){
Return nodeName;
}
Public void setNodeName (String nodeName ){
This. nodeName = nodeName;
}
Public long getFatherNodeId (){
Return fatherNodeId;
}
Public void setFatherNodeId (long fatherNodeId ){
This. fatherNodeId = fatherNodeId;
}
}
Public class ConstructorTree {
StringBuffer json = new StringBuffer ();
/**
*
* @ Title: getJson
* @ Description: Call the interface
* @ Author Administrator
* @ Param list
* @ Param node
* @ Return
*/
Public String getJson (List List, TreeNode node ){
Json = new StringBuffer ();
ConstructorJson (list, node );
String jsonDate = json. toString ();
Return ("[" + jsonDate + "]"). replaceAll (",]", "]");
}
/**
*
* @ Title: constructorJson
* @ Description: Construct a json tree.
* @ Author Administrator
* @ Param list
* @ Param treeNode
*/
@ SuppressWarnings ("unchecked ")
Public void constructorJson (List List, TreeNode treeNode ){
If (hasChild (list, treeNode )){
Json. append ("{id :");
Json. append (treeNode. getNodeId ());
Json. append (", text :");
Json. append (treeNode. getNodeName ());
Json. append (", children :[");
List ChildList = getChildList (list, treeNode );
Iterator iterator = childList. iterator ();
While (iterator. hasNext ()){
TreeNode node = (TreeNode) iterator. next ();
ConstructorJson (list, node );
}
Json. append ("]},");
} Else {
Json. append ("{id :");
Json. append (treeNode. getNodeId ());
Json. append (", text :");
Json. append (treeNode. getNodeName ());
Json. append ("},");
}
}
/**
*
* @ Title: getChildList
* @ Description: obtains the subnode list information.
* @ Author Administrator
* @ Param list
* @ Param node
* @ Return
*/
Public List GetChildList (List List, TreeNode node ){
List Li = new ArrayList ();
Iterator it = list. iterator ();
While (it. hasNext ()){
TreeNode n = (TreeNode) it. next ();
If (n. getFatherNodeId () = node. getNodeId ()){
Li. add (n );
}
}
Return li;
}
/**
*
* @ Title: hasChild
* @ Description: determines whether a subnode exists.
* @ Author Administrator
* @ Param list
* @ Param node
* @ Return
*/
Public boolean hasChild (List List, TreeNode node ){
Return getChildList (list, node). size ()> 0? True: false;
}
}