构建Json树形目录结构

   程序主要是拼装符合Json格式的树形数据文件,分两部分:

   一 表示节点的简单POJO   

 

   public class TreeNode {

       private long nodeId;
 
       private String nodeName;
 
       private long father_nodeId;
 
       public TreeNode(){}
 
      public TreeNode(long nodeId,String nodeName,long father_nodeId){
           this.nodeId=nodeId;
           this.nodeName=nodeName;
           this.father_nodeId=father_nodeId;
      }

 

       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 getFather_nodeId() {
            return father_nodeId;
     }

 

     public void setFather_nodeId(long fatherNodeId) {
          father_nodeId = fatherNodeId;
     }
}

 

 

   二  构建树的工具类

 

public class ConstructorTree {

 StringBuffer json=new StringBuffer(); 
 
 /**
  * 构建Json文件
  * @param list
  * @param node
  */
    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("},");    
        }    
            
    }    
   
    /**
     * 获得子节点列表信息
     * @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.getFather_nodeId()==node.getNodeId()){    
                li.add(n);    
            }    
        }    
        return li;    
    }
   
    /**
     * 判断是否有子节点
     * @param list
     * @param node
     * @return
     */
    public boolean hasChild(List list, TreeNode node){ 
        return getChildList(list,node).size()>0?true:false;  
    }
    public String getJson(List list, TreeNode node){  
     json = new StringBuffer();
     constructorJson(list,node);
     String jsonDate=json.toString();  
        return ("["+jsonDate+"]").replaceAll(",]", "]");
          
    }
}

你可能感兴趣的:(数据结构和算法)