json天气预报解析

来源:互联网 发布:算法研发工程师路线 编辑:程序博客网 时间:2024/04/30 04:49

1.中央气象台api:

http://www.weather.com.cn/data/sk/101010100.html

2.显示的json格式:

{"weatherinfo":{"city":"北京",
                              "cityid":"101010100",
                              "temp":"3",
                              "WD":"东北风",
                              "WS":"2级",
                              "SD":"60%",
                              "WSE":"2",
                              "time":"09:15",
                              "isRadar":"1",
                              "Radar":"JC_RADAR_AZ9010_JB"}
}

3.获取String类型的json格式数据(必须在libs目录下加入gson-2.2.2.jar)

String url = "http://www.weather.com.cn/data/sk/101010100.html";String jsonStr = getXmlString(url);

private String getXmlString(String path) {try {URL url = new URL(path);HttpURLConnection cn = (HttpURLConnection) url.openConnection();cn.setConnectTimeout(5 * 1000);cn.setRequestMethod("GET");InputStreamReader in = new InputStreamReader(cn.getInputStream());// 流的应用与读取BufferedReader bu = new BufferedReader(in);String line = bu.readLine().toString();System.out.println("流数据line========" + line);bu.close();in.close();return line;} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();System.out.println("查询失败,请检查网络...");return null;}}

4.解析json得到数据:

String jsonStr = getXmlString(url);// 开始解析xml数据if (jsonStr == null) {GlobalConstant.i("nothing json data");} else {String strObj = new String(jsonStr);try {JSONObject jsonObject = new JSONObject(strObj);JSONObject root = jsonObject.getJSONObject("weatherinfo");String item1 = root.getString("city");GlobalConstant.i("item1--->" + item1);} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();GlobalConstant.i("json err-->" + e);}}

5.输出结果:


1 0
原创粉丝点击