ExtJs树的递归算法(Java),Json格式
Java, ExtJs, Json, 递归, 算法
Java代码
public class Node { private int id; private int parentId; Node(){} Node(int id,int parentId){ this.id=id; this.parentId = parentId; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getParentId() { return parentId; } public void setParentId(int parentId) { this.parentId = parentId; } } 下面这个类先手工建立List,在实际应用中是从数据库读取List,然后再Main方法里调用递归方法,得到Json字符串 Java代码 import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Recursion { List nodeList =new ArrayList(); Recursion(){//构造方法里初始化模拟List Node node1 = new Node(1,0); Node node2 = new Node(2,1); Node node3 = new Node(3,1); Node node4 = new Node(4,2); Node node5 = new Node(5,2); Node node6 = new Node(6,2); Node node7 = new Node(7,6); Node node8 = new Node(8,6); nodeList.add(node1); nodeList.add(node2); nodeList.add(node3); nodeList.add(node4); nodeList.add(node5); nodeList.add(node6); nodeList.add(node7); nodeList.add(node8); } StringBuffer returnStr=new StringBuffer(); public void recursionFn(List list , Node node){ if(hasChild(list,node)){ returnStr.append("{id:"); returnStr.append(node.getId()); returnStr.append(",parentId:"); returnStr.append(node.getParentId()); returnStr.append(",children:["); List childList = getChildList(list,node); Iterator it = childList.iterator(); while(it.hasNext()){ Node n = (Node)it.next(); recursionFn(list,n); } returnStr.append("]},"); }else{ returnStr.append("{id:"); returnStr.append(node.getId()); returnStr.append(",parentId:"); returnStr.append(node.getParentId()); returnStr.append(",leaf:true},"); } } public boolean hasChild(List list, Node node){ //判断是否有子节点 return getChildList(list,node).size()>0?true:false; } public List getChildList(List list , Node node){ //得到子节点列表 List li = new ArrayList(); Iterator it = list.iterator(); while(it.hasNext()){ Node n = (Node)it.next(); if(n.getParentId()==node.getId()){ li.add(n); } } return li; } public String modifyStr(String returnStr){//修饰一下才能满足Extjs的Json格式 return ("["+returnStr+"]").replaceAll(",]", "]"); } public static void main(String[] args) { Recursion r = new Recursion(); r.recursionFn(r.nodeList, new Node(1,0)); System.out.println(r.modifyStr(r.returnStr.toString())); } } Main方法运行效果如下: [{id:1,parentId:0,children:[{id:2,parentId:1,children:[{id:4,parentId:2,leaf:true},{id:5,parentId:2,leaf:true},{id:6,par entId:2,children:[{id:7,parentId:6,leaf:true},{id:8,parentId:6,leaf:true}]}]},{id:3,parentId:1,leaf:true}]}] 在具体的应用中稍加修改即可