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

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查询省市县信息

  • 4
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值