在实战开发中经常有需要处理树形菜单、树形目录等等等业务需求。而对于这种产品,在设计数据库时也建议使用id<----->parentId的结构来做。但是最终前端显示多用hightChart或者Echart插件来实现。所以在给前端数据时,最好的做法就是把数据库结构话的数据处理成treeJson格式。
第一步:引入fastjson
com.alibaba fastjson${fastjson.version}
第二步:用到了工具内的JSONPath
JSONPath使用教程
public staticList tree(Object obj, String parentCodeFieldName, String parentCode, String currentCodeFieldName, String childrenFiledName, Class 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 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); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



