Java后台返回省市县树形结构

Java后台返回的数据格式如下:

Java后台返回省市县树形结构_第1张图片

实现方法为:

先查出所有的省份,将省份插入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 children = new ArrayList<>();
}

Service层:

    /**
     * 获取省市县树形结构
     *
     * @return
     */
    public List getProvince() {
        return apiMapper.getProvince();
    }

    public List getCity(String code) {
        List city = apiMapper.getCity(code);
        return city;
    }

    public List getCounty(String code) {
        List county = apiMapper.getCounty(code);
        return county;
    }

Controller层:

    @RequestMapping(value = "/getAreaTree", method = RequestMethod.GET)
    @ApiOperation(value = "获取省市县树形结构")
    public List getTree() {
        //查询所有省份,将省份下的城市 区县 学校信息存入对应的省份下
        List regionList = apiService.getProvince();
        for (int i = 0; i < regionList.size(); i++) {
            String code = regionList.get(i).getCode();
            regionList.get(i).setChildren(regionList);
            List 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 county = apiService.getCounty(cityCode);
                // 将区县信息插入城市子列表
                city.get(j).setChildren(county);
            }
        }
        return regionList;
    }

dao层和mapper文件省略,就是根据code查询省市县信息

你可能感兴趣的:(省市县树形结构,java)