java递归菜单树转换成json字符串
package com.cjonline.foundation.member.util; import java.util.ArrayList; import java.util.List; public class Tree { private static List<Person> dataSource=new ArrayList<Person>(); static{ Person p1 = new Person("1000","",1); Person p2 = new Person("1001","1000",2); Person p3 = new Person("1002","1000",1); Person p4 = new Person("1003","1001",2); Person p5 = new Person("1004","1001",1); Person p6 = new Person("1005","1001",1); Person p7 = new Person("1006","1002",1); Person p8 = new Person("1007","1002",1); Person p9 = new Person("1008","1002",1); dataSource.add(p1); dataSource.add(p2); dataSource.add(p3); dataSource.add(p4); dataSource.add(p5); dataSource.add(p6); dataSource.add(p7); dataSource.add(p8); dataSource.add(p9); } public static void main(String[] args) { StringBuffer sb = new StringBuffer(); Person p1 = new Person("1000","",1); findChilds(dataSource,sb,p1); sb.deleteCharAt(sb.length()-1); System.out.println(sb.toString()); } private static void findChilds(List<Person> pers,StringBuffer sb,Person person){ sb.append("{\"id\":\""+person.getId()+"\""); List<Person> temps = getChilds(pers,person); if(temps.size()>0){ sb.append(",child:["); for(Person ds : temps){ findChilds(pers,sb,ds); } sb.deleteCharAt(sb.length()-1); sb.append("]"); } sb.append("},"); } private static List<Person> getChilds(List<Person> pers,Person person){ List<Person> per= new ArrayList<Person>(); for(Person p : pers){ if(person.getId().equals(p.getParentId())){ per.add(p); } } return per; } }