这是ztree抽象类,方便扩展。
public abstract class AbstractZtree {
/**
* 默认初始化顶级id
*/
public static final String TOP = "0001";
//本级Id
protected String id;
//父级菜单的 id
protected String pId;
//中文名称
protected String name;
//点击地址
protected String url;
//是否展开
protected boolean open;
//是否为父节点
protected boolean isParent;
protected List children = new ArrayList();
public AbstractZtree() {
}
public AbstractZtree(String id, String pId, String name, boolean open, boolean isParent) {
super();
this.id = id;
this.pId = pId;
this.name = name;
this.open = open;
this.isParent = isParent;
}
... 大量get set 方法
继承类主要是测试Builder 只是测试Builder 所以就不做无限递归了
public class ZtreeDemoVo extends AbstractZtree{
public static final String TREE_NAME = "测试";
public ZtreeDemoVo() {
}
private ZtreeDemoVo(Builder builder){
super(builder.id, builder.pId, builder.name, builder.open, builder.isParent);
}
/**
* 传入上级编码 跟下级数据bean 生产二级节点。
* @param pid
*/
public void initChildren(String pid , List beans){
List ls = new ArrayList();
ZtreeDemoVo data = null;
for (Bean bean : beans) {
data = new ZtreeDemoVo
.Builder()
.id(bean.getId())
.pId(pid)
.name(bean.getName())
.open(false)
.isParent(false)
.build();
ls.add(data);
}
this.children = ls;
}
public static class Builder {
//本级Id
private String id = getTop();
//父级菜单的 id
private String pId = null;
//中文名称
private String name = TREE_NAME;
//是否展开
private boolean open = true;
//是否为父节点
private boolean isParent = true;
public Builder id(String id){
this.id = id;
return this;
}
public Builder pId(String pId){
this.pId = pId;
return this;
}
public Builder name(String name){
this.name = name;
return this;
}
public Builder open(Boolean open){
this.open = open;
return this;
}
public Builder isParent(Boolean isParent){
this.isParent = isParent;
return this;
}
public ZtreeDemoVo build(){
return new ZtreeDemoVo(this);
}
}
}
测试bean
public class Bean {
private String id;
private String pid;
private String name;
public String getId() {
return id;
}
public Bean() {
// TODO Auto-generated constructor stub
}
public Bean(String id, String pid, String name) {
super();
this.id = id;
this.pid = pid;
this.name = name;
}
... 大量get set 方法
测试类 这里的Json.toJson()就是bean 转json跟Gson什么的差不多的功能。
public class ZtreeTest {
@Test
public void ztree(){
List beans = new ArrayList();
Bean data = null;
for (int i = 0; i < 3; i++) { //模拟假数据
data = new Bean(String.valueOf(i), String.valueOf(i), String.valueOf(i));
beans.add(data);
}
ZtreeDemoVo vo = new ZtreeDemoVo.Builder().build();
vo.initChildren(vo.getId(),beans); //初始化二级数据
System.out.println(Json.toJson(vo));
}
}
结果
{
"id": "0001",
"name": "测试",
"open": true,
"isParent": true,
"children": [{
"id": "0",
"pId": "0001",
"name": "0",
"open": false,
"isParent": false,
"children": []
}, {
"id": "1",
"pId": "0001",
"name": "1",
"open": false,
"isParent": false,
"children": []
}, {
"id": "2",
"pId": "0001",
"name": "2",
"open": false,
"isParent": false,
"children": []
}]
}