获得树形json串
public class TreeNode {
private long nodeId;private String nodeName;
private long fatherNodeId;
public TreeNode() {
}
public TreeNode(long nodeId, String nodeName, long fatherNodeId) {
this.nodeId = nodeId;
this.nodeName = nodeName;
this.fatherNodeId = fatherNodeId;
}
public long getNodeId() {
return nodeId;
}
public void setNodeId(long nodeId) {
this.nodeId = nodeId;
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public long getFatherNodeId() {
return fatherNodeId;
}
public void setFatherNodeId(long fatherNodeId) {
this.fatherNodeId = fatherNodeId;
}
}
public class ConstructorTree {
StringBuffer json = new StringBuffer();
/**
*
* @Title: getJson
* @Description: 调用接口
* @author Administrator
* @param list
* @param node
* @return
*/
public String getJson(List<TreeNode> list, TreeNode node) {
json = new StringBuffer();
constructorJson(list, node);
String jsonDate = json.toString();
return ("[" + jsonDate + "]").replaceAll(",]", "]");
}
/**
*
* @Title: constructorJson
* @Description: 构建json树
* @author Administrator
* @param list
* @param treeNode
*/
@SuppressWarnings("unchecked")
public void constructorJson(List<TreeNode> list, TreeNode treeNode) {
if (hasChild(list, treeNode)) {
json.append("{id:");
json.append(treeNode.getNodeId());
json.append(",text:");
json.append(treeNode.getNodeName());
json.append(",children:[");
List<TreeNode> childList = getChildList(list, treeNode);
Iterator iterator = childList.iterator();
while (iterator.hasNext()) {
TreeNode node = (TreeNode) iterator.next();
constructorJson(list, node);
}
json.append("]},");
} else {
json.append("{id:");
json.append(treeNode.getNodeId());
json.append(",text:");
json.append(treeNode.getNodeName());
json.append("},");
}
}
/**
*
* @Title: getChildList
* @Description: 获得子节点列表信息
* @author Administrator
* @param list
* @param node
* @return
*/
public List<TreeNode> getChildList(List<TreeNode> list, TreeNode node) {
List<TreeNode> li = new ArrayList<TreeNode>();
Iterator it = list.iterator();
while (it.hasNext()) {
TreeNode n = (TreeNode) it.next();
if (n.getFatherNodeId() == node.getNodeId()) {
li.add(n);
}
}
return li;
}
/**
*
* @Title: hasChild
* @Description: 判断是否有子节点
* @author Administrator
* @param list
* @param node
* @return
*/
public boolean hasChild(List<TreeNode> list, TreeNode node) {
return getChildList(list, node).size() > 0 ? true : false;
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。