封装父子级关系

    public static JSONArray createTreeJson(List<?> list) throws Exception {
        JSONArray rootArray = new JSONArray();
        for (int i = 0; i < list.size(); i++) {
            Class resource = list.get(i).getClass();
            Object objectResource = list.get(i);
            // 接触私有化限制
            resource.getDeclaredField("parentId").setAccessible(true);
            resource.getDeclaredField("id").setAccessible(true);
            String ParentIdField = resource.getDeclaredField("parentId").get(objectResource).toString();
            if (ParentIdField.equals("0")) {
                //创建子节点分支
                JSONObject rootObj = createBranch(list, objectResource);
                rootArray.add(rootObj);
            }
        }
        return rootArray;
    }

    public static <T> JSONObject createBranch(List<?> list, Object currentNode) throws Exception {
        JSONObject currentObj = (JSONObject) JSONObject.toJSON(currentNode);
        JSONArray childArray = new JSONArray();
        for (int i = 0; i < list.size(); i++) {
            Class newNode = list.get(i).getClass();
            Class currentNodeClass = currentNode.getClass();
            // 解除私有化限制
            String ParentIdField = newNode.getDeclaredField("parentId").get(list.get(i)).toString();
            String idField = currentNodeClass.getDeclaredField("id").get(currentNode).toString();
            if (ParentIdField != null && ParentIdField.compareTo(idField) == 0) {
                JSONObject childObj = createBranch(list, list.get(i));
                childArray.add(childObj);
            }
        }
        if (!childArray.isEmpty()) {
            currentObj.put("children", childArray);
        }
        return currentObj;
    }

 

上一篇:利用java8的并行流实现多个接口同时请求,并合并结果


下一篇:Java解析嵌套Json字符串