数据库数据:
通过sq语句查询出 易于构建树形结构的数据【sql语句如下】:
后端数据的处理:
/**
* 构建类目下的树形结构
* @param shardingId
* @return
*/
@ChainedTransaction(mapper={IClassFicationMapper.class})
public DataResult constructTree(@RouteParam("IClassFicationMapper")Long shardingId){
//查询 易于构建树形结构的数据
List classFicationDOs=classFicationMapper.selectByParentId(shardingId, null);
//用于存在1级节点
JSONArray topArray=new JSONArray();
//树形的最大级数
final int maxLevel=10;
//用于构建同级的树
JSONArray temp=null;
for(ClassFicationDO classFicationDO:classFicationDOs) {
//用具计算存放在 temp 数组中索引位置,(即:1级存放在 索引为 0 位,2级存在在 1位,以此类推...)
Integer index=classFicationDO.getCfLevel()-1;
JSONObject jsonObject=new JSONObject();
jsonObject.put("id", classFicationDO.getId());
jsonObject.put("cfName", classFicationDO.getCfName());
jsonObject.put("childrens",new JSONArray());
if(index.equals(0)) { //当前类目为1级时,重新构建并保存到1级节点数组中
temp=new JSONArray(maxLevel);
topArray.add(jsonObject);
}
//若当前类目中不存在1级
if(temp==null) {
continue;
}
//将类目存放到相应的索引下
temp.set(index, jsonObject);
//将子级存放在到相应的父级节点下(即:若子级为 2级(索引为1)应该存放到父级1级(索引为0)的节点下,以此类推...)
if(index>0) {
temp.getJSONObject(--index).getJSONArray("childrens").add(jsonObject);
}
}
return DataResult.success(topArray, JSONArray.class);
}
处理后返回的树形json 数据: