有一个list List<Department> list
Department有3个属性 id name(部门名称)和fatherId(父部门的id)
怎么遍历才能生成 easyui tree需要的json
json格式如下
"[{\"id\":1,\"text\":\"My Documents\",\"children\":[{\"id\":11,\"text\":\"Photos\",\"state\":\"closed\",\"children\":[{\"id\":111,\"text\":\"Friend\"},{\"id\":112,\"text\":\"Wife\"}]},{\"id\":12,\"text\":\"Program Files\",\"children\":[{\"id\":121,\"text\":\"Intel\"}]},{\"id\":13,\"text\":\"index.html\"},{\"id\":14,\"text\":\"about.html\"},{\"id\":15,\"text\":\"welcome.html\"}]}]";
------解决思路----------------------
用个json转换插件,比如json-lib啊,gson啊之类的
------解决思路----------------------
json-lib就可以
使用方法
------解决思路----------------------
建议是json转成map
然后map操作就简单了,父子级id关系就很明显
------解决思路----------------------
public class TreeNode {把java类的属性都放进去,组成一颗树的形状,之后,使用json库一般就支持直接转了。Jackson库支持。
/**
* Logger for this class
*/
private static final Log LOGGER = LogFactory.getLog(TreeNode.class);
private String id; // 要显示的子节点的ID
private String text; // 要显示的子节点的 Text
private String iconCls; // 节点的图标
private String parentId; // 父节点的ID
private List<TreeNode> children; // 孩子节点的List
public TreeNode() {
super();
}
public TreeNode(String id, String text, String iconCls, String parentId,
List<TreeNode> children) {
super();
this.id = id;
this.text = text;
this.iconCls = iconCls;
this.parentId = parentId;
this.children = children;
}
public void addChild(TreeNode node) {
LOGGER.debug("addChild(TreeNode node=" + node + ") - start");
if (this.children == null) {
children = new ArrayList<TreeNode>();
children.add(node);
} else {
children.add(node);
}
LOGGER.debug("addChild(TreeNode node=" + node + ") - end");
}
public List<TreeNode> getChildren() {
return children;
}
public String getIconCls() {
return iconCls;
}
public String getId() {
return id;
}
public String getParentId() {
return parentId;
}
public String getText() {
return text;
}
public void setChildren(List<TreeNode> children) {
this.children = children;
}
public void setIconCls(String iconCls) {
this.iconCls = iconCls;
}
public void setId(String id) {
this.id = id;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public void setText(String text) {
this.text = text;
}
}
------解决思路----------------------
遍历list就用for循环 ,get(元素序号),遍历json,就相当于遍历map,根据键名获得键值就行了