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; }