分享一个工具类
/**
* Json字符串工具类
*
* @author yanwei
* remind:所有顶级菜单的pid为0才能正常迭代出对应的树
*/
public class JsonTree {
/**
* 根据id,pid和树要显示的属性生成树的Json字符串 ,字符串没有中括号,因为牵扯递归调用,不方便处理
*
* @param
* @param objs
* @param pidAttr
* @param idAttr
* @return
* @throws Exception
*/
public static String treeJson(long pid , List objs, StringBuilder builder, String pidAttr,
String idAttr,String name) throws Exception {
if (objs.size() == 0){
return "{\"children\":[]}";
}
for(Iterator iter = objs.iterator(); iter.hasNext();) {
T t = iter.next();
long id = getLong(t, idAttr);
long temp_pid = getLong(t, pidAttr);
String label = getValue(t, name);
if(pid == Long.MAX_VALUE){
break;
}
if(temp_pid == pid){
builder.append("{\"id\":\"").append(id).append("\",");
builder.append("\"name\":\"").append(label).append("\",");
if(isHasChildren(id, objs, pidAttr)) {
builder.append("\"children\":[");
treeJson(id, objs, builder, pidAttr, idAttr,name);
builder.append("]},");
}else{
builder.append("\"children\":[");
builder.append("],");
builder.deleteCharAt(builder.length() - 1).append("},");
}
}
}
if(builder.length()>=1){
builder.deleteCharAt(builder.length() - 1);
}
return builder.toString();
}
}
// 该方法给定一个id,一个list,判断是否包含子节点
private static boolean isHasChildren(long id , List objs, String pidAttr) throws Exception{
for(T t : objs){
long pid = getLong(t, pidAttr);
if(pid == id){
return true;
}
}
return false;
}
//利用反射,执行对象的方法,获取值
private static long getLong(T t, String attrName) throws Exception {
Field field = t.getClass().getDeclaredField(attrName);
if (!field.isAccessible()) {
field.setAccessible(true);
}
Object value = field.get(t);
if (value == null){
return Long.MAX_VALUE;
}else{
return Long.parseLong(value.toString());
}
}
//获取属性值,一般属性
private static String getValue(T t, String attrName) throws Exception {
Field field = t.getClass().getDeclaredField(attrName);
if (!field.isAccessible()) {
field.setAccessible(true);
}
Object value = field.get(t);
if (value == null){
return "\"\"";
}else{
return value.toString();
}
}