tree的数据格式为:
[{
"id": 1,
"text": "Node 1",
"state": "closed",
"children": [{
"id": 11,
"text": "Node 11"
},{
"id": 12,
"text": "Node 12"
}]
},{
"id": 2,
"text": "Node 2",
"state": "closed"
}]
Tree树的组装:
1:创建一个TreeVo类,并根据查询的数据封装List<TreeVo>
public class TreeVo implements java.io.Serializable{
private String id;
private String pid;
private String text;
private TreeVo parent;
private Integer index;
private List<TreeVo> children;
public TreeVo(){}
public TreeVo(Integer index) {
this.index = index;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getPid() {
// TODO Auto-generated method stub
return pid;
}
public TreeVo getParent() {
// TODO Auto-generated method stub
return parent;
}
public void setParent(TreeVo entity) {
// TODO Auto-generated method stub
this.parent=entity;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public List<TreeVo> getChildren() {
return children;
}
public void setChlidren(TreeVo entity) {
// TODO Auto-generated method stub
if(this.children==null){
this.children=new ArrayList<TreeVo>();
}
if(entity!=null){
this.children.add(entity);
}
}
/**
* 在当前节点上追加一个子节点
* @param entry
*/
public void addChildren(TreeVo entry) {
if (null == entry) {
return;
}
if (null == this.getChildren()) {
//this.children = new ArrayList<T>();
this.setChlidren(null);
}
if (!this.getChildren().contains(entry)) {
this.setChlidren(entry);
entry.setParent(this);
}
}
}
2:组装tree树需要的数据格式 :
Map<String,TreeVo> treeMap=new HashMap(0);
for(TreeVo vo : treeList){
treeMap.put(vo.getId(), vo);
}
for(int i=0; i<treeList.size(); i++){
TreeVo parent=treeMap.get(treeList.get(i).getPid());
if(parent!=null){
parent.addChildren(treeList.get(i));
treeList.remove(treeList.get(i));
i--;
}
}
JsonConfig config=new JsonConfig();
//过滤掉parent树形,防止JSON解析时出异常!
config.setExcludes(new String[]{"parent"});
JSONArray ja=JSONArray.fromObject(treeList, config);