由于项目需要将数据库中的一个层级表转换成json格式输出,在网上找了很久都没有找开合适的内容,要不是代码太复杂,就是不符合需求,所以就自己用递归写了一个无级树的代码。代码很简单就两个类一个TreeNode.java 和一个测试类Test.java(可直接运行)
在运行之前需要以下公共类:
commons-beanutils.jar
commons-collections.jar
commons-lang.jar
commons-logging.jar
ezmorph-1.0.6.jar
json-lib-2.3-jdk15.jar
package com.test;测试类 Test.java
import java.util.ArrayList;
public class TreeNode {
private String id;
private String pid;
private String name;
private String remark;
private ArrayList<TreeNode> children = new ArrayList<TreeNode>();
public TreeNode(String id, String pid, String name, String remark) {
this.id = id;
this.pid = pid;
this.name = name;
this.remark = remark;
}
public void add(TreeNode node) {//递归添加节点
if ("0".equals(node.pid)) {
this.children.add(node);
} else if (node.pid.equals(this.id)) {
this.children.add(node);
} else {
for (TreeNode tmp_node : children) {
tmp_node.add(node);
}
}
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public ArrayList<TreeNode> getChildren() {
return children;
}
public void setChildren(ArrayList<TreeNode> children) {
this.children = children;
}
}
package com.test;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class Test {
public static void main(String[] args) {
TreeNode root = new TreeNode("0", "0", "000000", "00JJJ");
TreeNode node = null;
node = new TreeNode("1", "0", "111111", "11AAA");
root.add(node);
node = new TreeNode("2", "0", "222222", "11BBB");
root.add(node);
node = new TreeNode("3", "2", "333333", "11CCC");
root.add(node);
// JSONObject obj = JSONObject.fromObject(root);//有根
JSONArray obj = JSONArray.fromObject(root.getChildren());// 不要根
System.out.println(obj.toString());
}
}