github下载地址(获取国家统计局的数据并转成json文件)
https://github.com/small-dream/China_Province_City
解析json文件
String file = "C:\\Users\\2020年10月中华人民共和国县以上行政区划代码.json";
InputStream inputStream = new FileInputStream(new File(file));
byte[] bytes = new byte[inputStream.available()];
StringBuffer buffer = new StringBuffer();
//读取文件
inputStream.read(bytes);
buffer.append(new String(bytes, Charsets.UTF_8));
inputStream.close();
//解析JSON文件
JSONArray all = JSONArray.parseArray(buffer.toString());
List<Province> provinces = new ArrayList<>(all.size());
for (int i = 0; i < all.size(); i++) {
JSONObject _province = all.getJSONObject(i);
//省
Province province = new Province();
province.setName(_province.getString("name"));
province.setCode(_province.getString("code"));
//市
JSONArray _cityList = _province.getJSONArray("cityList");
List<City> cityList = new ArrayList<>(_cityList.size());
for (int j = 0; j < _cityList.size(); j++) {
JSONObject _city = _cityList.getJSONObject(j);
City city = new City();
city.setCode(_city.getString("code"));
city.setName(_city.getString("name"));
city.setParentCode(_province.getString("code"));
//区
JSONArray _areaList = _city.getJSONArray("areaList");
List<Area> areaList = new ArrayList<>(_areaList.size());
for (int k = 0; k < _areaList.size(); k++) {
JSONObject _area = _areaList.getJSONObject(k);
Area area = new Area();
area.setCode(_area.getString("code"));
area.setName(_area.getString("name"));
area.setParentCode(_city.getString("code"));
areaList.add(area);
}
city.setAreaList(areaList);
cityList.add(city);
}
province.setCityList(cityList);
//到这里数据解析完成,全部存入provinces
provinces.add(province);
}