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;
}
}
posted @ 2020-07-31 09:30  光头...强  阅读(806)  评论(0编辑  收藏  举报