JAVA 生成樹形結構,並輸出成JSONArray串



import java.util.ArrayList;
import java.util.List;

public class InterfaceParametersListDTO {
/** 接口包含的參數明細 */
private List<InterfaceParametersDO> interfaceParametersDOList;

public List<InterfaceParametersDO> getInterfaceParametersDOList() {
return interfaceParametersDOList;
}

public void setInterfaceParametersDOList(List<InterfaceParametersDO> interfaceParametersDOList) {
this.interfaceParametersDOList = interfaceParametersDOList;
}

//建立樹形結構
private List<InterfaceParametersDO> builTree(){
List<InterfaceParametersDO> treeMenus =new ArrayList<InterfaceParametersDO>();
for(InterfaceParametersDO menuNode : getRootNode()) {
menuNode=buildChilTree(menuNode);
treeMenus.add(menuNode);
}
return treeMenus;
}

//遞歸,建立子樹形結構
private InterfaceParametersDO buildChilTree(InterfaceParametersDO pNode){
List<InterfaceParametersDO> chilMenus = new ArrayList<InterfaceParametersDO>();
for(InterfaceParametersDO menuNode : this.getInterfaceParametersDOList()) {
if(menuNode.getPatientId().equals(pNode.getId())) {
chilMenus.add(buildChilTree(menuNode));
}
}
pNode.setChildren(chilMenus);
return pNode;
}

//獲取根節點
private List<InterfaceParametersDO> getRootNode() {
List<InterfaceParametersDO> rootMenuLists =new ArrayList<InterfaceParametersDO>();
for(InterfaceParametersDO menuNode : this.getInterfaceParametersDOList()) {
if(StringUtils.isBlank(menuNode.getPatientId())) {
rootMenuLists.add(menuNode);
}
}
return rootMenuLists;
}

//返回樹形結構的JSONArray
public JSONArray getJSONOArray(){
JSONArray jsonArray = new JSONArray();
for(InterfaceParametersDO menuNode : builTree()) {
if (menuNode!=null){
JSONObject jsobj = getJsonObject(menuNode);
jsonArray.add(jsobj);
}
}
return jsonArray;
}

private JSONObject getJsonObject(InterfaceParametersDO menuNode) {
JSONObject jsobj = new JSONObject();
jsobj.put("parameterId", menuNode.getId());
jsobj.put("apiId ", menuNode.getApiId());
jsobj.put("patientId", menuNode.getPatientId());
jsobj.put("inOrOutType", menuNode.getInOrOutType());
jsobj.put("parameterEName", menuNode.getParameterEName());
jsobj.put("parameterCName", menuNode.getParameterCName());
jsobj.put("parameterType", menuNode.getParameterType());
jsobj.put("resinterfaceNo", menuNode.getParameterNo());
jsobj.put("remark", menuNode.getRemark());
jsobj.put("children",getChildrenArray(menuNode.getChildren()));
return jsobj;
}

/** 獲取子節點數組 */
private JSONArray getChildrenArray(List<InterfaceParametersDO> children){
JSONArray childrenJsonArray = new JSONArray();
if (children != null && children.size() >0){
for(InterfaceParametersDO t : children){
childrenJsonArray.add(getJsonObject(t));
}
}
return childrenJsonArray;
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM