• 封装父子级关系


     /**
         * @param parentName 父级编号对应的字段名
         * @param idName 主键的字段名称
         * @param list 数据库查询出来的数据
         * */
        public static JSONArray createTreeJson(List<?> list,String parentName,String idName) 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);
                // 解除私有化限制
                for (Field field : resource.getDeclaredFields()) {
                    if (field.getName().equals(parentName)) {
                        field.setAccessible(true);
                        String parentIdField = field.get(objectResource).toString();
                        if (parentIdField.equals("0")) {
                            //创建子节点分支
                            JSONObject rootObj = createBranch(list, objectResource,parentName,idName);
                            rootArray.add(rootObj);
                        }
                    }
                }
            }
            return rootArray;
        }
    
        public static JSONObject createBranch(List<?> list, Object currentNode,String parentName,String idName) throws Exception {
            JSONObject currentObj = (JSONObject) JSONObject.toJSON(currentNode);
            JSONArray childArray = new JSONArray();
            String parentIdField = null;
            String idField = null;
            for (int i = 0; i < list.size(); i++) {
                Class newNode = list.get(i).getClass();
                Class currentNodeClass = currentNode.getClass();
                for (Field field : newNode.getDeclaredFields()){
                    if (field.getName().equals(parentName)) {
                        field.setAccessible(true);
                        // 反射获取值
                        parentIdField = field.get(list.get(i)).toString();
                    }
                }
                for (Field field : currentNodeClass.getDeclaredFields()) {
                    if (field.getName().equals(idName)) {
                        field.setAccessible(true);
                        // 反射获取值
                        idField = field.get(currentNode).toString();
                    }
                }
    
                if (parentIdField != null && idField != null && parentIdField.equals(idField)) {
                    JSONObject childObj = createBranch(list, list.get(i),parentName,idName);
                    childArray.add(childObj);
                }
            }
            if (!childArray.isEmpty()) {
                currentObj.put("children", childArray);
            }
            return currentObj;
        }
  • 相关阅读:
    安卓输入法
    android问题
    速查
    Iphone幻灯片效果+背景音乐
    MBProgressHUD使用
    画图
    textmate 的快捷键
    设置Table Cell的背景图的类
    Objectc 一些代码规范
    效果收集
  • 原文地址:https://www.cnblogs.com/huqi96/p/14633277.html
Copyright © 2020-2023  润新知