数据库中表数据,如下图:
实现的需求是,如果suporgcode数据为null 的情况下,表示在一级节点 "请选择" 的二级节点,然后是如:3和36 是1的子节点,一步一步的节点延伸
java代码拼接方式如下:
/**
* 拼接成json类型 事故类型
* @author 刘仁奎
*/
public String createJSONData(String instcode){
// 查询一级节点
String sql="select orgcode,orgname,suporgcode from swe_emerplanorg where instcode='"+instcode+"' and suporgcode is null order by orgcode";
List list=jdbcT.queryForList(sql);
StringBuffer json=new StringBuffer("[{\"id\":\"0\",\"text\":\"请选择\",\"children\":[");// 初始化根节点
if(list!=null && list.size()>0){
for(int i=0; i
Map v_map = (Map)list.get(i);
json.append(this.getChildren(instcode,v_map.get("ORGCODE").toString()));// 获取子节点
}
json=new StringBuffer(json.substring(0, json.length()-1)+"]}]");
}
System.out.println(json);
return json.toString();
}
/**
* 得到子节点
*/
private String getChildren(String instcode,String orgcode){
String sql = "select orgcode,orgname,suporgcode from swe_emerplanorg where instcode ='"+instcode+"' and orgcode='"+orgcode+"' and suporgcode is null order by orgcode";
List list=jdbcT.queryForList(sql);
StringBuffer child_json=new StringBuffer();
if(list!=null && list.size()>0){
for(int i=0; i
Map v_map = (Map)list.get(i);
child_json.append("{\"id\":\""+v_map.get("ORGCODE").toString().trim()+"\",");
child_json.append("\"text\":\""+v_map.get("ORGNAME").toString().trim()+"\"");
String sql_2 = "select orgcode,orgname,suporgcode from swe_emerplanorg where instcode ='"+instcode+"' and suporgcode='"+v_map.get("ORGCODE")+"' order by orgcode";
List t_l=jdbcT.queryForList(sql_2);
if(t_l!=null && t_l.size()>0){
child_json.append(",\"children\":[");
for(int t=0; t
Map t_m = (Map)t_l.get(t);
child_json.append("{\"id\":\""+t_m.get("ORGCODE").toString().trim()+"\",");
child_json.append("\"text\":\""+t_m.get("ORGNAME").toString().trim()+"\"");
child_json.append(getNodes(instcode,t_m.get("ORGCODE").toString()));// 下级节点
}
child_json=new StringBuffer(child_json.substring(0, child_json.lastIndexOf(","))+"]},");
}else{
child_json.append("},");
}
}
}else{
child_json.append("},");
}
return child_json.toString();
}
/**
* 获得节点
*/
public String getNodes(String instcode,String orgcode){
String sql = "select orgcode,orgname,suporgcode from swe_emerplanorg where instcode ='"+instcode+"' and suporgcode ='"+orgcode+"' order by orgcode";
List list=jdbcT.queryForList(sql);
StringBuffer j_s=new StringBuffer();
if(list!=null && list.size()>0){
j_s.append(",\"children\":[");
for(int i=0; i
Map t_m = (Map)list.get(i);
j_s.append("{\"id\":\""+t_m.get("ORGCODE").toString().trim()+"\",");
j_s.append("\"text\":\""+t_m.get("ORGNAME").toString().trim()+"\"");
j_s.append(getNodes(instcode,t_m.get("ORGCODE").toString()));
}
}else{
j_s.append("},");
}
if(j_s.toString().contains("children")){
j_s=new StringBuffer(j_s.substring(0, j_s.lastIndexOf(",")));
j_s.append("]},");
}
return j_s.toString();
}
最终的实现图如下