`
天涯海角tour
  • 浏览: 170225 次
  • 性别: Icon_minigender_1
  • 来自: 郑州
社区版块
存档分类
最新评论

树形结构的json数据源,

阅读更多


package test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.baihe.entity.Node;

public class bd {

List nodeList =new ArrayList();  
bd(){//构造方法里初始化模拟List  
        Node node1 = new Node("01","0");    
        Node node2 = new Node("0102","01");    
        Node node3 = new Node("0103","01");    
        Node node4 = new Node("010201","0102");    
        Node node5 = new Node("010202","0102");    
      
        nodeList.add(node1);    
        nodeList.add(node2);    
        nodeList.add(node3);    
        nodeList.add(node4);    
        //nodeList.add(node5);    
       
    }  
    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().endsWith(node.getId())){    
                li.add(n);    
            }    
        }    
        return li;    
    }  
    public String modifyStr(String returnStr){//修饰一下才能满足Extjs的Json格式  
        return ("["+returnStr+"]").replaceAll(",]", "]");  
          
    }  
    public static void main(String[] args) {    
    bd r = new bd();    
        r.recursionFn(r.nodeList, new Node("01","0"));    
        System.out.println(r.modifyStr(r.returnStr.toString()));    
    }    
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics