依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
业务代码
public JSONArray areasTree() {
List<CommonAreas> commonAreas = new ArrayList<>();
return List2TreeUtil.listToTree(JSONArray.parseArray(JSON.toJSONString(commonAreas )), "areaId", "parentId", "children");
}
return null;
}
CommonAreas实体类
package com.xian.member.domain.po;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false)
public class CommonAreas implements Serializable {
private static final long serialVersionUID=1L;
private Integer areaId;
private Integer parentId;
private String areaName;
private Integer areaType;
private Integer sort;
}
List2TreeUtil 实体类
package com.devinx.common.util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class List2TreeUtil {
public static JSONArray listToTree(JSONArray arr, String id, String pid, String child) {
JSONArray r = new JSONArray();
JSONObject hash = new JSONObject();
for (int i = 0; i < arr.size(); i++) {
JSONObject json = (JSONObject) arr.get(i);
hash.put(json.getString(id), json);
}
for (int j = 0; j < arr.size(); j++) {
JSONObject aVal = (JSONObject) arr.get(j);
String pidStr = "";
if (null != aVal.get(pid)) {
pidStr = aVal.get(pid).toString();
}
JSONObject hashVP = (JSONObject) hash.get(pidStr);
if (hashVP != null) {
if (hashVP.get(child) != null) {
JSONArray ch = (JSONArray) hashVP.get(child);
ch.add(aVal);
hashVP.put(child, ch);
} else {
JSONArray ch = new JSONArray();
ch.add(aVal);
hashVP.put(child, ch);
}
} else {
r.add(aVal);
}
}
return r;
}
}