public String createTree(List<UserOreWizard> ListUserOreWizard){
//得到所有的用户集合
HashMap nodeList =new HashMap();
Node root =null;
for (int i=0;i<ListUserOreWizard.size();i++) {
List<UserOreWizard> listS = wizardServiceApi.queryOreWizardChildren(ListUserOreWizard.get(i).getUserName());
Node node = new Node();
node.id = (String) ListUserOreWizard.get(i).getUserName();
node.text = (String) ListUserOreWizard.get(i).getUserName();
node.parentId = (String) ListUserOreWizard.get(i).getRefUserName();
nodeList.put(node.id, node);
}
Set entrySet = nodeList.entrySet();
for (Iterator it = entrySet.iterator(); it.hasNext();) {
Node node = (Node) ((Map.Entry) it.next()).getValue();
if (node.parentId == null || node.parentId.equals("")) {
root = node;
} else {
((Node) nodeList.get(node.parentId)).addChild(node);
}
}
String w = root.toString();
return "{Rows:"+"["+w+"],"+"\"Total\":"+"30}";
}
节点类(实体)与tree结构组织相对应即可
class Node {
/**
* 节点编号
*/
public String id;
/**
* 节点内容
*/
public String text;
/**
* 父节点编号
*/
public String parentId;
/**
* 孩子节点列表
*/
private Children children = new Children();
// 先序遍历,拼接JSON字符串
public String toString() {
String result ="{"
+ "id:\" " + id + "\""
+ ", text: \"" + text + "\""
+",state:\""+true+"\"";
if (children != null && children.getSize() != 0) {
result += ", children: " + children.toString();
} else {
result += ",leaf: \"true\""+",expanded:\"false\"";
}
return result + "}";
}
// 兄弟节点横向排序
public void sortChildren() {
if (children != null && children.getSize() != 0) {
children.sortChildren();
}
}
// 添加孩子节点
public void addChild(Node node) {
this.children.addChild(node);
}
class Children {
private List list = new ArrayList();
public int getSize() {
return list.size();
}
public void addChild(Node node) {
list.add(node);
}
// 拼接孩子节点的JSON字符串
public String toString() {
String result = "[";
for (Iterator it = list.iterator(); it.hasNext();) {
result += ((Node) it.next()).toString();
result += ",";
}
result = result.substring(0, result.length() - 1);
result += "]";
return result;
}
// 孩子节点排序
public void sortChildren() {
// 对本层节点进行排序
// 可根据不同的排序属性,传入不同的比较器,这里传入ID比较器
Collections.sort(list, new NodeIDComparator());
// 对每个节点的下一层节点进行排序
for (Iterator it = list.iterator(); it.hasNext();) {
((Node) it.next()).sortChildren();
}
}
}
/**
* 节点比较器
*/
class NodeIDComparator implements Comparator {
// 按照节点编号比较
public int compare(Object o1, Object o2) {
int j1 = Integer.parseInt(((Node)o1).id);
int j2 = Integer.parseInt(((Node)o2).id);
return (j1 < j2 ? -1 : (j1 == j2 ? 0 : 1));
}
}
}