"[\n" +
" {\n" +
" \"menuCode\": \"M000002\",\n" +
" \"menuName\": \"a1\",\n" +
" \"parentId\": \"M000000\",\n" +
"\t\t\t\t \"url\": \"/xxxx\",\n" +
"\"sort\": \"1\",\n" +
" \"isButton\": 1,\n" +
" \"sysNum\": \" P0001\"\n" +
" },\n" +
" {\n" +
" \"menuCode\": \"M000002001\",\n" +
" \"menuName\": \"a2\",\n" +
" \"parentId\": \"M000002\",\n" +
" \"url\": \"/xxx\",\n" +
"\"sort\": \"1\",\n" +
" \"isButton\": 0,\n" +
" \"sysNum\": \" P0001\"\n" +
" },\n" +
" {\n" +
" \"menuCode\": \"M000002002\",\n" +
" \"menuName\": \"a3\",\n" +
" \"parentId\": \"M000002\",\n" +
" \"url\": \"/xxxx\",\n" +
"\"sort\": \"2\",\n" +
" \"isButton\": 0,\n" +
" \"sysNum\": \" P0001\"\n" +
" }\n" +
" {\n" +
" \"menuCode\": \"M000002003\",\n" +
" \"menuName\": \"a4\",\n" +
" \"parentId\": \"M000002\",\n" +
" \"url\": \"/xxxx\",\n" +
"\"sort\": \"3\",\n" +
" \"isButton\": 0,\n" +
" \"sysNum\": \" P0001\"\n" +
" }\n" +
" {\n" +
" \"menuCode\": \"M000002004\",\n" +
" \"menuName\": \"a5\",\n" +
" \"parentId\": \"M000002\",\n" +
" \"url\": \"/xxxx\",\n" +
"\"sort\": \"4\",\n" +
" \"isButton\": 0,\n" +
" \"sysNum\": \" P0001\"\n" +
" }\n" +
" {\n" +
" \"menuCode\": \"M000002005\",\n" +
" \"menuName\": \"a6\",\n" +
" \"parentId\": \"M000002\",\n" +
" \"url\": \"/xxxx\",\n" +
"\"sort\": \"5\",\n" +
" \"isButton\": 0,\n" +
" \"sysNum\": \" P0001\"\n" +
" }\n" +
" {\n" +
" \"menuCode\": \"M0000020051\",\n" +
" \"menuName\": \"a7\",\n" +
" \"parentId\": \"M000002005\",\n" +
" \"url\": \"/xxxxx\",\n" +
"\"sort\": \"1\",\n" +
" \"isButton\": 0,\n" +
" \"sysNum\": \" P0001\"\n" +
" }\n" +
" {\n" +
" \"menuCode\": \"M0000020052\",\n" +
" \"menuName\": \"a8\",\n" +
" \"parentId\": \"M000002005\",\n" +
" \"url\": \"/xxxx\",\n" +
"\"sort\": \"2\",\n" +
" \"isButton\": 0,\n" +
" \"sysNum\": \" P0001\"\n" +
" }\n" +
" ],\n"
// JSON数组扁平化结构 转换 树形菜单嵌套结构
public JSONArray parseMenus(JSONArray treeData){
JSONArray res = new JSONArray();
// 需要删除的菜单
List<String> delMenu = new ArrayList<>();
// 查找对应的子菜单 采用双层for循环 找到对应子菜单
for (int i = 0; i < treeData.size(); i++) {
JSONObject jsonObject = (JSONObject) treeData.get(i);
JSONArray childrens = new JSONArray();
for (int j = 0; j < treeData.size(); j++) {
JSONObject jsonObjectChild = (JSONObject) treeData.get(j);
if(jsonObject.get("menuCode").equals(jsonObjectChild.get("parentId"))){
childrens.add(jsonObjectChild);
delMenu.add((String) jsonObjectChild.get("menuCode"));
}
}
jsonObject.put("children", childrens);
}
// 判断哪些是子菜单 移除
for (int i = 0; i < treeData.size(); i++) {
JSONObject jsonObject = (JSONObject) treeData.get(i);
if(!delMenu.contains((String)jsonObject.get("menuCode"))){
res.add(jsonObject);
}
}
return res;
}
JSON数组扁平化结构 转换 树形菜单嵌套结构
于 2022-03-25 09:14:26 首次发布