/**
* 构建 ExtJS Tree 使用的Store
* @param prentid
* @param jsArr
* @return
*/
public static JSONArray buildStore4ExtTree(int prentid, JSONArray jsArr){
JSONArray retArray = new JSONArray();
for (int i = 0; i < jsArr.size(); i++) {
JSONObject obj = jsArr.getJSONObject(i);
if(prentid == obj.getIntValue("pid")){
retArray.add(obj);
}
}
for (int i = 0; i < retArray.size(); i++) {
JSONObject obj = retArray.getJSONObject(i);
JSONArray tmpArr = buildStore4ExtTree(obj.getIntValue("id"),jsArr);
if(!tmpArr.isEmpty()){
obj.put("children", tmpArr);
obj.put("leaf",0);
}
}
return retArray;
}
public static void main(String[] args) {
JSONObject obj1 = new JSONObject();
obj1.put("pid", 0);
obj1.put("id", 1);
obj1.put("name", "name1");
JSONObject obj2 = new JSONObject();
obj2.put("pid", 0);
obj2.put("id", 2);
obj2.put("name", "name2");
JSONObject obj3 = new JSONObject();
obj3.put("pid", 2);
obj3.put("id", 3);
obj3.put("name", "name3");
JSONObject obj4 = new JSONObject();
obj4.put("pid", 2);
obj4.put("id", 4);
obj4.put("name", "name4");
JSONObject obj5 = new JSONObject();
obj5.put("pid", 4);
obj5.put("id", 5);
obj5.put("name", "name5");
JSONObject obj6 = new JSONObject();
obj6.put("pid", 5);
obj6.put("id", 6);
obj6.put("name", "name6");
JSONObject obj7 = new JSONObject();
obj7.put("pid", 6);
obj7.put("id", 7);
obj7.put("name", "name7");
JSONObject obj8 = new JSONObject();
obj8.put("pid", 5);
obj8.put("id", 8);
obj8.put("name", "name8");
JSONObject obj9 = new JSONObject();
obj9.put("pid", 4);
obj9.put("id", 9);
obj9.put("name", "name9");
JSONObject obj10 = new JSONObject();
obj10.put("pid", 6);
obj10.put("id", 10);
obj10.put("name", "name10");
JSONObject obj11 = new JSONObject();
obj11.put("pid", 5);
obj11.put("id", 11);
obj11.put("name", "name11");
JSONObject obj12 = new JSONObject();
obj12.put("pid", 10);
obj12.put("id", 12);
obj12.put("name", "name12");
JSONArray arr = new JSONArray();
arr.add(obj1);
arr.add(obj2);
arr.add(obj3);
arr.add(obj4);
arr.add(obj5);
arr.add(obj6);
arr.add(obj7);
arr.add(obj8);
arr.add(obj9);
arr.add(obj10);
arr.add(obj11);
arr.add(obj12);
System.out.println(buildStore4ExtTree(0,arr));
}