JAVA 轉換 樹結構數據


JAVA 轉換 樹結構數據

第一步:引入fastjson

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>${fastjson.version}</version>
</dependency>

第二步:用到了工具內的JSONPath

JSONPath使用教程

    /**
     * 樹轉換
     *
     * @param obj                  需要轉換的對象
     * @param parentCodeFieldName  父標識字段名
     * @param parentCode           父標識值
     * @param currentCodeFieldName 當前標識字段名
     * @param childrenFiledName    子樹的字段名
     * @param c                    需要轉換的Class類型
     * @param <T>                  泛型
     * @return 返回List<T>
     */
    public static <T> List<T> tree(Object obj, String parentCodeFieldName, String parentCode, String currentCodeFieldName, String childrenFiledName, Class<T> c) {
        long t1 = System.currentTimeMillis();
        String jsonStr = JSON.toJSONString(obj);
        log.debug("樹轉換開始 >>>>>>>>>>>>>>>> {}", JSON.toJSONString(obj));
        //獲取第一層級的數據
        JSONArray jsonArray = (JSONArray) JSONPath.read(jsonStr, "$[" + parentCodeFieldName + "=" + parentCode + "]");
        if (CollectionUtils.isEmpty(jsonArray)) {
            //為空的話直接返回空集合
            return Lists.newArrayList();
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String code = jsonObject.getString(currentCodeFieldName);
            treeChildren(jsonStr, jsonObject, parentCodeFieldName, code, currentCodeFieldName, childrenFiledName);
        }
        List<T> list = JSONArray.parseArray(jsonArray.toString(), c);
        log.debug("樹轉換結束, 轉換時間: {} ms . >>>>>>>>>>>>>>>> {}", (System.currentTimeMillis() - t1), JSON.toJSONString(list));
        return list;
    }

    private static void treeChildren(String jsonStr, JSONObject currentJsonObj, String parentCodeFieldName, String parentCode, String currentCodeFieldName, String childrenFiledName) {
        JSONArray jsonArray = (JSONArray) JSONPath.read(jsonStr, "$[" + parentCodeFieldName + "=" + parentCode + "]");
        if (CollectionUtils.isEmpty(jsonArray)) {
            return;
        }
        currentJsonObj.put(childrenFiledName, jsonArray);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String code = jsonObject.getString(currentCodeFieldName);
            treeChildren(jsonStr, jsonObject, parentCodeFieldName, code, currentCodeFieldName, childrenFiledName);
        }
    }

趙小胖個人博客


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM