【Java小项目】简单的天气预报

    昨天看到一个百度的天气API

介绍:http://apistore.baidu.com/apiworks/servicedetail/478.html

接口:http://apis.baidu.com/heweather/weather/free

看到返回的数据类型十JSON,由于没接触过JSON所以就做了这个小东西试试。


     分析json用org.json这包。写了个递归来将最内层的键值对放到Map中,Map的Key值为该节点的所有父节点的名称的组合。

static Map<String,String> all=new HashMap<String, String>();

public static void toMap(String exName,String jsonStr){
        try {
            JSONObject jO=new JSONObject(jsonStr);
            Iterator iterator=jO.keys();
            while(iterator.hasNext()){
                String key= (String) iterator.next();
                if(jO.get(key) instanceof JSONObject){
                        //System.out.println(((JSONObject) jO.get(key)).length());
                        toMap(exName + "_" + key, jO.get(key).toString());
                }else if(jO.get(key) instanceof JSONArray){
                    JSONArray jA=(JSONArray) jO.get(key);
                    for(int i=0;i<jA.length();i++){
                        toMap(exName+"_"+key,jA.get(i).toString());
                    }
                }else {
                    while(all.containsKey(exName+"_"+key))
                        exName+="*";
                    //System.out.println(exName+"_"+key+":"+jO.getString(key));
                    all.put(exName+"_"+key,jO.getString(key));
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }




这个程序的精华就是上面的代码。其他的就不贴出来了。

完整代码

git@osc:http://git.oschina.net/A_yes/Weather


posted @ 2015-11-21 18:43  A_yes  阅读(519)  评论(0编辑  收藏  举报