国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

JAVA如何轉換樹結構數據代碼實例

瀏覽:200日期:2022-09-03 16:38:15

在實戰開發中經常有需要處理樹形菜單、樹形目錄等等等業務需求。而對于這種產品,在設計數據庫時也建議使用id<----->parentId的結構來做。但是最終前端顯示多用hightChart或者Echart插件來實現。所以在給前端數據時,最好的做法就是把數據庫結構話的數據處理成treeJson格式。

第一步:引入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); } }

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Java
相關文章:
主站蜘蛛池模板: 长宁县| 调兵山市| 德清县| 天水市| 延川县| 镇坪县| 新沂市| 方山县| 张掖市| 怀远县| 公安县| 甘洛县| 灵石县| 浦县| 忻城县| 城市| 衡山县| 宜兰县| 灵武市| 乐业县| 西青区| 于田县| 望奎县| 阳曲县| 沂南县| 密山市| 青岛市| 离岛区| 肇庆市| 金堂县| 淄博市| 芷江| 巴马| 民和| 琼结县| 西昌市| 长丰县| 济宁市| 桐柏县| 普兰店市| 扎囊县|