Java后台返回的数据格式如下:
实现方法为:
先查出所有的省份,将省份插入children数组,再查询parentId为省份id的城市列表,将城市插入children数组,再查询parentId为城市id的区县列表,将区县插入children数组。
下面为具体实现代码
实体类:
@Data
public class Region implements Serializable {
private Integer id;
private String name;
private String parentId;
private String code;
private Integer level;
private List<Region> children = new ArrayList<>();
}
Service层:
/**
* 获取省市县树形结构
*
* @return
*/
public List<Region> getProvince() {
return apiMapper.getProvince();
}
public List<Region> getCity(String code) {
List<Region> city = apiMapper.getCity(code);
return city;
}
public List<Region> getCounty(String code) {
List<Region> county = apiMapper.getCounty(code);
return county;
}
Controller层:
@RequestMapping(value = "/getAreaTree", method = RequestMethod.GET)
@ApiOperation(value = "获取省市县树形结构")
public List<Region> getTree() {
//查询所有省份,将省份下的城市 区县 学校信息存入对应的省份下
List<Region> regionList = apiService.getProvince();
for (int i = 0; i < regionList.size(); i++) {
String code = regionList.get(i).getCode();
regionList.get(i).setChildren(regionList);
List<Region> city = apiService.getCity(code);
// 将城市信息插入省份子列表
regionList.get(i).setChildren(city);
for (int j = 0; j < city.size(); j++) {
String cityCode = String.valueOf(city.get(j).getCode());
List<Region> county = apiService.getCounty(cityCode);
// 将区县信息插入城市子列表
city.get(j).setChildren(county);
}
}
return regionList;
}
dao层和mapper文件省略,就是根据code查询省市县信息