jQuery EasyUI:根据数据库内容生成适合于easyui-tree的JSON数据格式

 

1,jQuery EasyUI中easyui-tree特定的JSON数据格式

复制代码
 1 [
 2 {"id":1,"text":"某公司","children":[
 3     {"id":2,"text":"生产部"},
 4     {"id":4,"text":"质检部","children":[
 5         {"id":3,"text":"销售部"},
 6         {"id":5,"text":"后勤部"},
 7         {"id":6,"text":"人事部"},
 8         {"id":7,"text":"财务部"},
 9         {"id":8,"text":"IT部"}]
10     }]
11 }
12 ]
复制代码

2,从数据库中查询出来的数据保存在一个List中。

其中字段Parent_Department_ID表明该节点的父节点。

则在数据库中查询出来的数据保存在List中对应数据结构中树的双亲表示法。对该树进行遍历的同时生成相应的JSON代码。

3,根据上述思想进行的具体实现

 
public string GetDepartmentTree()
 {<br>            //查询数据库,数据保存在List中
     List<department> queryDepart=_departmentService.LoadEntities(u=>true).ToList<department>();
     string departmentTree=null;
//遍历整个树,寻找根节点
     foreach (department d in queryDepart)
     {
         if (d.Parent_Department_ID == -1)
         {
             departmentTree="\"id\":"+d.Department_ID+",\"text\":\""+d.Department_Name+"\",";
             <br>            //调用FindChild方法,开始遍历整个树,寻找当前节点的子节点。   
             string child = FindChild(d.Department_ID, queryDepart);
             if (child != null)
             {
                 departmentTree += child;
             }
 
             departmentTree = "[{" + departmentTree + "}]";
         }
     }
 
     return departmentTree;
 }
 
 private string FindChild(int id, List<department> queryDepart)
 {
     bool flag = false;
     string departmentChild =null;
     foreach (department d in queryDepart)
     {
         string anotherChild = null;
         if (d.Parent_Department_ID == id)//寻找到子节点
         {<br>           
             anotherChild = "\"id\":" + d.Department_ID + ",\"text\":\"" + d.Department_Name + "\",";
             <br>            string child = FindChild(d.Department_ID, queryDepart);
             if (child != null)
             {
               
                 anotherChild = anotherChild + child ;
             }
             if (anotherChild[anotherChild.Length - 1] == ',')
             {
                 anotherChild = anotherChild.Remove(anotherChild.Length - 1);
             }
             anotherChild = "{" + anotherChild + "}";
 
             departmentChild += anotherChild+",";
         }
         else
         {
             flag = false;
         }           
 
     }
     if (departmentChild != null)
     {
         departmentChild = departmentChild.Remove(departmentChild.Length - 1);
         departmentChild = "\"children\":[" + departmentChild + "]";
     }
 
     return departmentChild;
 
 }
 
  
posted @ 2013-11-08 21:51  mythp  阅读(486)  评论(0编辑  收藏  举报