在实战开发中经常有需要处理树形菜单,树形目录等等等业务需求。而对于这种产品,在设计数据库时也建议使用id<- - - - -→parentId的结构来做。但是最终前端显示多用hightChart或者Echart插件来实现,所以在给前端数据时,最好的做法就是把数据库结构话的数据处理成treeJson格式。
第一步:引入fastjson
& lt; dependency> & lt; groupId> com.alibaba & lt; artifactId> fastjson & lt; version> $ {fastjson.version} & lt;/version> & lt;/dependency>
第二步:用到了工具内的JSONPath
JSONPath使用教程
/* * *树转换 * * @param obj需要转换的对象 * @param parentCodeFieldName父标识字段名 * @param parentCode父标识值 * @param currentCodeFieldName当前标识字段名 * @param childrenFiledName子树的字段名 * @param c需要转换的类类型 * @param & lt; T>泛型 * @return返回List*/公共静态& lt; T>List 树(parentCode parentCodeFieldName对象obj,字符串,字符串,字符串currentCodeFieldName,字符串childrenFiledName Class c) { 长t1=System.currentTimeMillis (); 字符串jsonStr=JSON.toJSONString (obj); log.debug(“树转换开始在在在在在在在在在在在在在在在在{}”,JSON.toJSONString (obj));//获取第一层级的数据 JSONPath JSONArray JSONArray JSONArray=()。读(jsonStr,“美元[+ parentCodeFieldName + "=" + parentCode + "]”); 如果(CollectionUtils.isEmpty(获取)){//为空的话直接返回空集合 返回Lists.newArrayList (); } for (int i=0;我& lt;jsonArray.size ();我+ +){ JSONObject JSONObject=jsonArray.getJSONObject(我); 字符串代码=jsonObject.getString (currentCodeFieldName); parentCodeFieldName treeChildren (jsonStr jsonObject,代码,currentCodeFieldName, childrenFiledName); } List =JSONArray.parseArray列表(jsonArray.toString (), c); log.debug(“树转换结束,转换时间:{}。在在在在在在在在在在在在在在在在{}”,(System.currentTimeMillis () - t1), JSON.toJSONString(列表)); 返回列表; } 私有静态孔隙treeChildren(字符串jsonStr JSONObject currentJsonObj,字符串parentCodeFieldName,字符串parentCode,字符串currentCodeFieldName,字符串childrenFiledName) { JSONPath JSONArray JSONArray JSONArray=()。读(jsonStr,“美元[+ parentCodeFieldName + "=" + parentCode + "]”); 如果(CollectionUtils.isEmpty(获取)){ 返回; } currentJsonObj。把(jsonArray childrenFiledName,); for (int i=0;我& lt;jsonArray.size ();我+ +){ JSONObject JSONObject=jsonArray.getJSONObject(我); 字符串代码=jsonObject.getString (currentCodeFieldName); parentCodeFieldName treeChildren (jsonStr jsonObject,代码,currentCodeFieldName, childrenFiledName); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。