java 删除树节点 ,树以json形式存储(备忘)


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


public class Test {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String jsonStr = "{\"id\":\"0\",\"text\":\"我的收藏\",\"cls\":\"folder\",\"children\":[{\"id\":\"27260236332789670000\",\"text\":\"we\",\"cls\":\"folder\",\"children\":[{\"id\":\"27264047306094694000\",\"text\":\"asd\",\"leaf\":true}]},{\"id\":\"4315427192432198700\",\"text\":\"模块管理\",\"leaf\":true}]}";
JSONObject oldObj = JSONObject.fromObject(jsonStr);
String removedId = "27264047306094694000";

Test t = new Test();
JSONObject newObj = t.removeJSONObject(oldObj, removedId);
System.out.println(newObj);
}

/**
* 根据id删除JSONObject对象
* @param oldJsonObj
* @param removedJsonId
* @return
*/
public JSONObject removeJSONObject(JSONObject oldJsonObj,String removedJsonId){
JSONObject newJsonObj = null;
if(oldJsonObj == null){
return null;
}

//获取要删除的JSONObject
JSONObject removeObj = this.getRemovedJSONObject(oldJsonObj,removedJsonId);
if(removeObj == null){
return oldJsonObj;
}

String oldJsonObjStr = oldJsonObj.toString();
String removeObjStr = removeObj.toString();

//将原有JSONObject字符串中删除查询到的JSONObject字符串
String newJsonObjStr = oldJsonObjStr.replace(removeObjStr+",", "");
newJsonObjStr = newJsonObjStr.replace(removeObjStr, "");

if(newJsonObjStr == null){
return null;
}

//重新获取删除后的JSONObject
newJsonObj = JSONObject.fromObject(newJsonObjStr);
return newJsonObj;
}

/**
* 获取要删除的JSONObject
* @param jsonObj
* @param removedId
* @return
*/
private JSONObject getRemovedJSONObject(JSONObject jsonObj,String removedId){
JSONObject removeObj = null;
//获取id
String nodeId = jsonObj.getString("id");

if(removedId.equals(nodeId)){
return jsonObj;
}else{
if(!jsonObj.containsKey("children")){
return null;
}

//查询该JSONObject中的子节点
JSONArray subJsonArr = (JSONArray) jsonObj.get("children");
if(subJsonArr == null || subJsonArr.size() == 0){
return null;
}

for(Object obj : subJsonArr){
//继续递归查询
removeObj = this.getRemovedJSONObject((JSONObject)obj,removedId);
if(removeObj != null){
break;
}
}
}
return removeObj;
}

}

你可能感兴趣的:(java)