如下,我们要返回下面的数据格式
{ "value": "3", "label": "安徽省", "children": [ { "value": "安庆市", "label": "36", "children1s": [ { "label": "398", "value": "迎江区" }, { "label": "399", "value": "大观区" }, { "label": "400", "value": "宜秀区" }, { "label": "401", "value": "桐城市" }, { "label": "402", "value": "怀宁县" }, { "label": "403", "value": "枞阳县" }, {
那么可以通过构造辅助类来完成
这里因为这里是三级,所以我就构造了三个辅助类
@Getter@Setterpublic class Data { private String value; private String label; private Listchildren;}
@Setter@Getterpublic class Children { private String value; private String label; private Listchildren1s;}
@Getter@Setterpublic class Children1 { private String label; private String value;}
我的mapper
//查询所有的省 @Select("select * from zone where pid = 1") ListselectProvince(); //查询该省所有的市 @Select("select * from zone where pid =#{provinceId}") List selectCityByProvinceId(String provinceId); //查询该市对应的县 @Select("select * from zone where pid =#{cityId}") List selectCountyByCityId(String cityId);
接下来是我的serviceimpl
@Override public Result selectAll() { List dataList = null; try { dataList = new ArrayList(); Listprovinces = zoneInfoMapper.selectProvince(); for (ZoneInfo province : provinces) { Data data = new Data(); data.setValue(String.valueOf(province.getId())); data.setLabel(province.getDistrict()); List cities = zoneInfoMapper.selectCityByProvinceId(String.valueOf(province.getId())); List childrenList = new ArrayList (); for (ZoneInfo city : cities) { Children children = new Children(); children.setLabel(String.valueOf(city.getId())); children.setValue(city.getDistrict()); childrenList.add(children); List counties = zoneInfoMapper.selectCountyByCityId(String.valueOf(city.getId())); List children1s = new ArrayList (); for (ZoneInfo county : counties) { Children1 children1 = new Children1(); children1.setLabel(String.valueOf(county.getId())); children1.setValue(county.getDistrict()); children1s.add(children1); } children.setChildren1s(children1s); } data.setChildren(childrenList); dataList.add(data); } } catch (Exception e) { Logger.logMsg(4, e.getMessage()); return Result.build(500, ErrorCode.UNKNOWN_ERROR.getStatusMsg()); } return Result.ok(dataList); }
这里需要注意的是
Data data = new Data();需要在for循环里面创建,因为对于不同的province都是一个data,然后每一个data最终添加到datalist里面。如果是在for循环外面实例化,就会被覆盖掉,导致datalist里面的数据只有最后一个
同样的下面的children以及children1也一样