返回三級聯動的JSON資料
阿新 • • 發佈:2019-02-03
如下,我們要返回下面的資料格式
{ "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
@Setter
public class Data {
private String value;
private String label;
private List<Children> children;
}
@Setter @Getter public class Children { private String value; private String label; private List<Children1> children1s; }
@Getter
@Setter
public class Children1 {
private String label;
private String value;
}
我的mapper
//查詢所有的省 @Select("select * from zone where pid = 1") List<ZoneInfo> selectProvince(); //查詢該省所有的市 @Select("select * from zone where pid =#{provinceId}") List<ZoneInfo> selectCityByProvinceId(String provinceId); //查詢該市對應的縣 @Select("select * from zone where pid =#{cityId}") List<ZoneInfo> selectCountyByCityId(String cityId);
接下來是我的serviceimpl
@Override
public Result selectAll() {
List<Data> dataList = null;
try {
dataList = new ArrayList<Data>();
List<ZoneInfo> provinces = zoneInfoMapper.selectProvince();
for (ZoneInfo province : provinces) {
Data data = new Data();
data.setValue(String.valueOf(province.getId()));
data.setLabel(province.getDistrict());
List<ZoneInfo> cities = zoneInfoMapper.selectCityByProvinceId(String.valueOf(province.getId()));
List<Children> childrenList = new ArrayList<Children>();
for (ZoneInfo city : cities) {
Children children = new Children();
children.setLabel(String.valueOf(city.getId()));
children.setValue(city.getDistrict());
childrenList.add(children);
List<ZoneInfo> counties = zoneInfoMapper.selectCountyByCityId(String.valueOf(city.getId()));
List<Children1> children1s = new ArrayList<Children1>();
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也一樣