Android访问某个网页时网页会返回一个Inputstream流,这个流所包含的内容是一个json对象,比如天气预报网页的接口(http://www.weather.com.cn/data/cityinfo/101270101.html) ,如果把这个json对象当作String类来处理的话,就太麻烦了。还好,对于这样结构的数据,有json对象帮我们处理。具体可以这样。因为SDK中已经提供了JSON类,所以我们可以直接用,不用像java中要自己导入对于的jar包。
具体包在:org.json.* ; 在这里包下面有4个json类和一个json异常,分别是JSONArray JSONObject JSONStringer JSONTokener JSONException
Public void getWeather(){ String TAG= “Weather” ; String str = “” ; String date = “” ; url = new URL(urlString); httpConn = (HttpURLConnection) url.openConnection(); InputStream in = httpConn.getInputStream(); BufferedReader br = new BufferedReader( new InputStreamReader(in,"UTF-8")); while((str=br.readLine()) !=null){ Log.e(TAG, "天气内容是:"+str); date += str ; } JSONObject jsonDate = new JSONObject(date); SONObject jsonWeather = jsonDate.getJSONObject("weatherinfo");
Log(TAG, jsonDate.getJSONObject("city")); Log(TAG, jsonDate.getJSONObject("cityid ")); Log(TAG, jsonDate.getJSONObject("weather ")); Log(TAG, jsonDate.getJSONObject("temp2")); Log(TAG, jsonDate.getJSONObject("temp1")); Log(TAG, jsonDate.getJSONObject("ptime ")); }
|
|