您的位置:首页 > Web前端 > JavaScript

获得树形json串

2015-12-27 09:45 543 查看
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;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: