android json解析使用总结(二)-—天气预报的实现

 Android json解析使用总结(二)


       在前一篇《android json解析使用总结(一)》中介绍了一些关于json的基础知识,这一篇主要通过一个例子来实际演示一下android中如何解析从服务器或其他地方返回的json格式的数据。本次主要实现的是天气预报例子,里面主要涉及到“百度车联网API的使用”、“android Json解析”、等知识点,通过这个简单的demo,我们便可以熟悉如何解析json格式的数据。

        首先,我们从“百度车联网API官网”中获取key,这是我们能否使用百度提供的服务的关键,具体的步骤不详述。通过这个API我们可以从浏览器端查看获取天气json格式的数据,如下所示:


天气URL:

  1. http://api.map.baidu.com/telematics/v3/weather?location=常州&output=json&ak=ECIqazfmQFiEj0HAZKupo44x  


Json格式为:

  1. {  
  2.     "error"0,  
  3.     "status""success",  
  4.     "date""2015-08-06",  
  5.     "results": [  
  6.         {  
  7.             "currentCity""常州",  
  8.             "pm25""68",  
  9.             "index": [  
  10.                 {  
  11.                     "title""穿衣",  
  12.                     "zs""炎热",  
  13.                     "tipt""穿衣指数",  
  14.                     "des""天气炎热,建议着短衫、短裙、短裤、薄型T恤衫等清凉夏季服装。"  
  15.                 },  
  16.                 {  
  17.                     "title""洗车",  
  18.                     "zs""较适宜",  
  19.                     "tipt""洗车指数",  
  20.                     "des""较适宜洗车,未来一天无雨,风力较小,擦洗一新的汽车至少能保持一天。"  
  21.                 },  
  22.                 {  
  23.                     "title""旅游",  
  24.                     "zs""一般",  
  25.                     "tipt""旅游指数",  
  26.                     "des""天气较好,温度高,让人感觉热,幸好风比较大,能缓解炎热的天气。外出旅游请注意防暑降温和防晒。"  
  27.                 },  
  28.                 {  
  29.                     "title""感冒",  
  30.                     "zs""少发",  
  31.                     "tipt""感冒指数",  
  32.                     "des""各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。"  
  33.                 },  
  34.                 {  
  35.                     "title""运动",  
  36.                     "zs""较适宜",  
  37.                     "tipt""运动指数",  
  38.                     "des""天气较好,但因气温较高且风力较强,请适当降低运动强度并注意户外防风。"  
  39.                 },  
  40.                 {  
  41.                     "title""紫外线强度",  
  42.                     "zs""中等",  
  43.                     "tipt""紫外线强度指数",  
  44.                     "des""属中等强度紫外线辐射天气,外出时建议涂擦SPF高于15、PA+的防晒护肤品,戴帽子、太阳镜。"  
  45.                 }  
  46.             ],  
  47.             "weather_data": [  
  48.                 {  
  49.                     "date""周四 08月06日 (实时:31℃)",  
  50.                     "dayPictureUrl""http://api.map.baidu.com/images/weather/day/duoyun.png",  
  51.                     "nightPictureUrl""http://api.map.baidu.com/images/weather/night/duoyun.png",  
  52.                     "weather""多云",  
  53.                     "wind""东南风3-4级",  
  54.                     "temperature""36 ~ 27℃"  
  55.                 },  
  56.                 {  
  57.                     "date""周五",  
  58.                     "dayPictureUrl""http://api.map.baidu.com/images/weather/day/duoyun.png",  
  59.                     "nightPictureUrl""http://api.map.baidu.com/images/weather/night/zhenyu.png",  
  60.                     "weather""多云转阵雨",  
  61.                     "wind""东南风3-4级",  
  62.                     "temperature""35 ~ 27℃"  
  63.                 },  
  64.                 {  
  65.                     "date""周六",  
  66.                     "dayPictureUrl""http://api.map.baidu.com/images/weather/day/zhenyu.png",  
  67.                     "nightPictureUrl""http://api.map.baidu.com/images/weather/night/zhenyu.png",  
  68.                     "weather""阵雨",  
  69.                     "wind""东风4-5级",  
  70.                     "temperature""32 ~ 26℃"  
  71.                 },  
  72.                 {  
  73.                     "date""周日",  
  74.                     "dayPictureUrl""http://api.map.baidu.com/images/weather/day/zhenyu.png",  
  75.                     "nightPictureUrl""http://api.map.baidu.com/images/weather/night/zhenyu.png",  
  76.                     "weather""阵雨",  
  77.                     "wind""东南风4-5级",  
  78.                     "temperature""31 ~ 26℃"  
  79.                 }  
  80.             ]  
  81.         }  
  82.     ]  
  83. }  

     

         通过以上对json格式的数据分析,我们可以知道:这里面既包含简单的JSONObject对象如“status、date”等节点,又包含复杂的JSONArray对象如“results、index、weather_data”节点,属于一个混合模型的json格式数据,这就需要我们一步一步来解析。

       第一步,在本地新建一个WeatherBean用来存放解析到的天气数据,里面主要有“日期、风向、气温...”等字段

  1. package com.lj.weather.model;  
  2.   
  3. public class WeatherInfo {  
  4.   
  5.     private String dateWeek="";  
  6.     private String nightPictureUrl="";  
  7.     private String dayPictureUrl = "http://api.map.baidu.com/images/weather/day/duoyun.png";  
  8.     private String weather = "多云转晴";  
  9.     private String wind = "北风3-4级";  
  10.     private String temperature = "22 ~ 12℃";  
  11.   
  12.     public WeatherInfo() {  
  13.     };  
  14.       
  15.       
  16.     public void setDateWeek(String dateWeek){  
  17.         this.dateWeek=dateWeek;  
  18.     }  
  19.     public String getDateWeek(){  
  20.         return dateWeek;  
  21.     }  
  22.       
  23.     public void setdayPictureUrl(String dayPictureUrl){  
  24.         this.dayPictureUrl=dayPictureUrl;  
  25.     }  
  26.     public String getdayPictureUrl(){  
  27.         return dayPictureUrl;  
  28.     }  
  29.       
  30.       
  31.     public void setnightPictureUrl(String nightPictureUrl){  
  32.         this.nightPictureUrl=nightPictureUrl;  
  33.     }  
  34.     public String getnightPictureUrl(){  
  35.         return nightPictureUrl;  
  36.     }  
  37.       
  38.     public void setweather(String weather){  
  39.         this.weather=weather;  
  40.     }  
  41.     public String getweather(){  
  42.         return weather;  
  43.     }  
  44.       
  45.     public void setwind(String wind){  
  46.         this.wind=wind;  
  47.     }  
  48.     public String getwind(){  
  49.         return wind;  
  50.     }  
  51.       
  52.       
  53.     public void settemperature(String temperature){  
  54.         this.temperature=temperature;  
  55.     }  
  56.     public String gettemperature(){  
  57.         return temperature;  
  58.     }  
  59. }  

          第二步,写一个工具类,用于网络请求根据url获取json格式的天气数据并将其转化为字符串输出,
  1. package com.lj.weather.utils;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.InputStreamReader;  
  5.   
  6. import org.apache.http.HttpResponse;  
  7. import org.apache.http.client.methods.HttpGet;  
  8. import org.apache.http.impl.client.DefaultHttpClient;  
  9.   
  10. public class JSONUtils {  
  11.   
  12.     public JSONUtils (){};  
  13.     /** 
  14.      * 通过url 向服务器发送请求,服务器返回json数据 
  15.      * @param url 
  16.      *          url地址 
  17.      * @return 
  18.      *          string类型的json格式数据 
  19.      */  
  20.     public String getJSON(String url){  
  21.         StringBuilder builder=new StringBuilder();  
  22.         HttpGet httpRequest=new HttpGet(url);  
  23.         try {  
  24.              HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);  
  25.                 if (httpResponse.getStatusLine().getStatusCode() == 200) {  
  26.                     BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(),  
  27.                             "UTF-8"));  
  28.                     for (String s = reader.readLine(); s != null; s = reader.readLine()) {  
  29.                         builder.append(s);  
  30.                     }  
  31.                 }  
  32.         } catch (Exception e) {  
  33.             e.printStackTrace();  
  34.         }  
  35.         return builder.toString();  
  36.     }  
  37. }  
      

       第三步,我们便开始具体的解析上面获取到的json格式的字符串天气数据。代码里我都有详细的注释,所以就不多加解释了。

  1. package com.lj.weather.act;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import org.apache.http.impl.conn.tsccm.WaitingThread;  
  7. import org.json.JSONArray;  
  8. import org.json.JSONException;  
  9. import org.json.JSONObject;  
  10.   
  11. import com.lj.weather.R;  
  12. import com.lj.weather.adapter.NextWeatherAdapter;  
  13. import com.lj.weather.model.WeatherDetailInfo;  
  14. import com.lj.weather.model.WeatherInfo;  
  15. import com.lj.weather.utils.JSONUtils;  
  16.   
  17. import android.R.string;  
  18. import android.app.Activity;  
  19. import android.os.Bundle;  
  20. import android.os.Handler;  
  21. import android.os.Message;  
  22. import android.util.Log;  
  23. import android.widget.ListView;  
  24. import android.widget.TextView;  
  25. import android.widget.Toast;  
  26.   
  27. /** 
  28.  * 简单的天气预报显示界面 
  29.  *  
  30.  * @author Administrator 
  31.  *  
  32.  */  
  33. public class WeatherInfoShowAct extends Activity {  
  34.   
  35.     private String text = "";  
  36.     private TextView item_date;  
  37.     private TextView item_wind;  
  38.     private TextView item_temperature;  
  39.     private TextView item_weather;  
  40.     private JSONUtils jsonUtils;  
  41.     private WeatherInfo weatherInfo, weatherInfo1;  
  42.     private List<WeatherInfo> weatherInfoList;  
  43.     private String uri = "http://api.map.baidu.com/telematics/v3/weather?location=常州&output=json&ak=ECIqazfmQFiEj0HAZKupo44x";  
  44.   
  45.     private ListView listView;  
  46.     private NextWeatherAdapter adapter;  
  47.   
  48.     private Handler mHandler = new Handler() {  
  49.         public void handleMessage(Message msg) {  
  50.             if (msg.what == 1) {  
  51.                   
  52.                 //服务器返回的天气jsonText文本  
  53.                 String infoString = (String) msg.obj;  
  54.                   
  55.                 //天气数据list,今天,明天、后天、大后天  
  56.                 weatherInfoList = getWeatherInfo(infoString);  
  57.                 Log.d("Main""" + weatherInfoList.size());  
  58.                 adapter = new NextWeatherAdapter(weatherInfoList, WeatherInfoShowAct.this);  
  59.                 listView.setAdapter(adapter);  
  60.   
  61.                 item_date.setText(weatherInfo1.getDateWeek());  
  62.                 item_wind.setText(weatherInfo1.getwind());  
  63.                 item_temperature.setText(weatherInfo1.gettemperature());  
  64.                 item_weather.setText(weatherInfo1.getweather());  
  65.             }  
  66.         };  
  67.     };  
  68.   
  69.     @Override  
  70.     protected void onCreate(Bundle savedInstanceState) {  
  71.         super.onCreate(savedInstanceState);  
  72.         setContentView(R.layout.activity_weather_main);  
  73.         initView();  
  74.   
  75.     }  
  76.   
  77.     private void initView() {  
  78.         jsonUtils = new JSONUtils();  
  79.         listView = (ListView) findViewById(R.id.head_list);  
  80.         new Thread() {  
  81.             public void run() {  
  82.                 //根据url获得jsontext的天气数据  
  83.                 text = jsonUtils.getJSON(uri);  
  84.                 //刷新UI  
  85.                 Message message = new Message();  
  86.                 message.what = 1;  
  87.                 message.obj = text;  
  88.                 mHandler.sendMessage(message);  
  89.             };  
  90.         }.start();  
  91.   
  92.         item_date = (TextView) findViewById(R.id.head_date);  
  93.         item_temperature = (TextView) findViewById(R.id.head_temperature);  
  94.         item_weather = (TextView) findViewById(R.id.head_weather);  
  95.         item_wind = (TextView) findViewById(R.id.head_wind);  
  96.     }  
  97.   
  98.     private List<WeatherInfo> getWeatherInfo(String jsonStr) {  
  99.         try {  
  100.             JSONObject jsonObjectFirst = new JSONObject(jsonStr);  
  101.             /** error */  
  102.             if (jsonObjectFirst.get("error").equals(0)) {  
  103.   
  104.                 Log.d("error""" + jsonObjectFirst.get("error"));  
  105.                 Log.d("status""" + jsonObjectFirst.get("status"));  
  106.                 Log.d("date""" + jsonObjectFirst.get("date"));  
  107.   
  108.                 /** results */  
  109.                 JSONArray jsonArrayResults = (JSONArray) jsonObjectFirst.get("results");  
  110.   
  111.                 /** weather_data */  
  112.                 //为什么要get(0)?因为它属于第一个数组里面,其实总共只有一个数组  
  113.                 JSONObject jsonObjectWeatherData = (JSONObject) jsonArrayResults.get(0);  
  114.                   
  115.                 //获取当前城市  
  116.                 Log.d("currentCity", jsonObjectWeatherData.getString("currentCity"));  
  117.                 //获取当前城市的PM值  
  118.                 Log.d("pm25", jsonObjectWeatherData.getString("pm25"));  
  119.                   
  120.                   
  121.                 JSONArray jsonArrayWeatherData = (JSONArray) jsonObjectWeatherData.get("weather_data");  
  122.                   
  123.                 weatherInfoList = new ArrayList<WeatherInfo>();  
  124.                 for (int i = 0; i < 4; i++) {  
  125.                     JSONObject jsonObjectFour = (JSONObject) jsonArrayWeatherData.get(i);  
  126.                       
  127.                     //明天、后天、大后天数据  
  128.                     if (i >= 1) {  
  129.                         weatherInfo = new WeatherInfo();  
  130.                         weatherInfo.setDateWeek("" + jsonObjectFour.get("date"));  
  131.                         weatherInfo.setdayPictureUrl("" + jsonObjectFour.get("dayPictureUrl"));  
  132.                         weatherInfo.setnightPictureUrl("" + jsonObjectFour.get("nightPictureUrl"));  
  133.                         weatherInfo.setweather("" + jsonObjectFour.get("weather"));  
  134.                         weatherInfo.setwind("" + jsonObjectFour.get("wind"));  
  135.                         weatherInfo.settemperature("" + jsonObjectFour.get("temperature"));  
  136.                         weatherInfoList.add(weatherInfo);  
  137.                     } else {  
  138.                         //今天数据  
  139.                         weatherInfo1 = new WeatherInfo();  
  140.                         weatherInfo1.setDateWeek("" + jsonObjectFour.get("date"));  
  141.                         weatherInfo1.setdayPictureUrl("" + jsonObjectFour.get("dayPictureUrl"));  
  142.                         weatherInfo1.setnightPictureUrl("" + jsonObjectFour.get("nightPictureUrl"));  
  143.                         weatherInfo1.setweather("" + jsonObjectFour.get("weather"));  
  144.                         weatherInfo1.setwind("" + jsonObjectFour.get("wind"));  
  145.                         weatherInfo1.settemperature("" + jsonObjectFour.get("temperature"));  
  146.                     }  
  147.                 }  
  148.   
  149.                 Log.d("size""" + weatherInfoList.size());  
  150.             } else {  
  151.                 Toast.makeText(WeatherInfoShowAct.this"天气数据解析出错"1).show();  
  152.             }  
  153.   
  154.         } catch (JSONException e) {  
  155.             e.printStackTrace();  
  156.         }  
  157.         return weatherInfoList;  
  158.     }  
  159. }  
 

       最后,我们运行一下查看最后的效果:



       以上便是解析的全部过程,在这个demo中主要涉及到了网络请求、线程的使用、百度车联网服务的使用以及json数据的解析,在这个demo基础上,我们可以稍微修改一下,譬如增加刷新按钮、增加城市选择等便可以做出一个天气APP来,最后附上源码。


        源码下载地址


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值