中国天气网城市代码Json数据

Posted by 移影残风 on March 13, 2019

城市代码列表的接口:

http://mobile.weather.com.cn/js/citylist.xml

打开控制台里,将citylist.xml请求右键”SAVE AS”保存下来,或者直接用下载工具也行

xml文件里几乎包含了所有国家的城市数据,可以将其他国家的数据过滤掉,只留下中国的数据

于是我用Java处理了一下

String[] province = new String[]{"北京","天津","河北","山西","内蒙古","辽宁","吉林","黑龙江","上海","江苏","浙江","安徽","福建","江西","山东","河南","湖北","湖南","广东","广西","海南","重庆","四川","贵州","云南","西藏","陕西","甘肃","青海","宁夏","新疆"};
List<String> provinceList = Arrays.asList(province);
File file = new File("citylist.xml");
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(file);
Element rootElement = document.getRootElement();
Element cElement = rootElement.element("c");
List<Map<String, String>> mapList = new ArrayList<>();
for (Iterator it = cElement.elementIterator(); it.hasNext();) {
    Map<String, String> map = new HashMap<>();
    Element element = (Element) it.next();
    String d1 = element.attribute("d1").getValue();
    String d2 = element.attribute("d2").getValue();
    String d3 = element.attribute("d3").getValue();
    String d4 = element.attribute("d4").getValue();
    if (!provinceList.contains(d4)) {
        continue;
    }
    map.put("cityCode", d1);
    map.put("cityName", d2);
    map.put("cityPinyin", d3);
    map.put("province", d4);
    mapList.add(map);
}
Gson gson = new Gson();
String s = gson.toJson(mapList);
System.out.println(s);
FileUtils.writeStringToFile(new File("citylist.json"), s, "utf-8");

生成的Json文件

cn_weather_citylist.json

压缩后的:

cn_weather_citylist_compressed.json