分享

一起来开发Android的天气软件(四)

 厦港小镇 2017-08-11

        离上一篇文章过去才4、5天,我们赶紧趁热打铁继续完成该系列的天气软件的开发。承接上一章的内容使用Volley实现网络的通信,返回给我们的是这一串Json数据{"weatherinfo":{"city":"杭州","cityid":"101210101","temp1":"1℃","temp2":"10℃","weather":"多云转晴","img1":"n1.gif","img2":"d0.gif","ptime":"18:00"}},不知有没有同学跟着我的步骤已经得到了以上的Json数据呢,接下来我们需要在我们的Android对以上数据解析!Lets Go!

一、什么是Json?

     Json是一种类似于XML的通用数据交换格式,具有比XML更高的传输效率,体积较小,在网络传输时也可以更节省流量。但缺点也有,相比于XML语义性更差,看起来远不如XML直观。

     从结构上看,所有的数据(data)最终都可以分解成三种类型,但现在基本上常用的就是映射(mapping)这种类型,一个名/值对(Name/value),即数据有一个名称,还有一个与之相对应的值,这又称作散列(hash)或字典(dictionary),比如"首都:北京"。它的规格呢也是非常简单固定的。

(1) 并列的数据之间用逗号(",")分隔,如"city":"杭州","cityid":"101210101",city与cityid两个数据之间是用,隔开的

(2) 映射用冒号(":")表示。如"city":"杭州"

(3) 并列数据的集合(数组)用方括号("[]")表示。比如如果返回的数据是有好几天的,那么天气的数据就会有好几组,会返回类似以下的数据形式"weatherinfo":[{"city":"杭州","cityid":"101210101","temp1":"1℃","temp2":"10℃","weather":"多云转晴","img1":"n1.gif","img2":"d0.gif","ptime":"18:00"},{"city":"杭 州","cityid":"101210101","temp1":"1℃","temp2":"10℃","weather":"多云转晴","img1":"n1.gif","img2":"d0.gif","ptime":"18:00"}]

(4) 映射的集合(对象)用大括号("{}")表示。例如中国天气网给我们返回的首先是一整个是Weather对象,然后里头包含一个Weatherinfo对象。

二、如何解析Json数据?

     我们先使用最简单的方法解析中国天气网返回的数据。

     

  1. /** 
  2.      * 解析服务器返回的JSON数据,并将解析出的数据存储到本地。 
  3.      */  
  4.     public static void handleWeatherResponse(Context context, String response) {  
  5.         try {  
  6.             JSONObject jsonObject = new JSONObject(response);  
  7.             JSONObject weatherInfo = jsonObject.getJSONObject("weatherinfo");  
  8.             String cityName = weatherInfo.getString("city");  
  9.             String weatherCode = weatherInfo.getString("cityid");  
  10.             String temp1 = weatherInfo.getString("temp1");  
  11.             String temp2 = weatherInfo.getString("temp2");  
  12.             String weatherDesp = weatherInfo.getString("weather");  
  13.             String publishTime = weatherInfo.getString("ptime");  
  14.             saveWeatherInfo(context, cityName, weatherCode, temp1, temp2,  
  15.                     weatherDesp, publishTime);  
  16.         } catch (JSONException e) {  
  17.             e.printStackTrace();  
  18.         }  
  19.     }  

     将服务器返回的response通过创建一个JSONObject对象 jsonobject,再通过weatherinfo这个key值去获取它所对应weatherinfo所包括的属性,之后就通过getString()通过键值对映射的方法一个个获取其中的对象值啦!是不是觉得写起来好麻烦啊,有重复啊!无脑操作的代码要重复写好几遍了。

三、使用Gson解析数据?

     如果你认为JSONObject解析JSON数据的方法已经足够简单,那你真的太容易满足了,Gson开源库可以让解析数据简单到难以置信的!不过万事的开头你还得先去下载一下GSONde jar包,导入自己的程序文件里。

     然后呢我们再看一下我们要解析的Json数据格式{"weatherinfo":{"city":"杭州","cityid":"101210101","temp1":"1℃","temp2":"10℃","weather":"多云转晴","img1":"n1.gif","img2":"d0.gif","ptime":"18:00"}},根据其格式我们先定义一个weather类,

  1. package com.melhc.model;  
  2.   
  3. public class Weather {  
  4.     private Weatherinfo weatherinfo;  
  5.   
  6.     public Weatherinfo getWeatherinfo() {  
  7.         return weatherinfo;  
  8.     }  
  9.   
  10.     public void setWeatherInfo(Weatherinfo weatherinfo) {  
  11.         this.weatherinfo = weatherinfo;  
  12.     }  
  13. }  

    然后这个weather类里有一个weatherinfo对象,这个对象呢又包含着city,cityid,temp1等等的对象,该怎么办呢!

  1. package com.melhc.model;  
  2.   
  3.   
  4.   
  5. public class Weatherinfo {  
  6.    private String city;  
  7.    private String cityid;  
  8.    private String temp1;  
  9.    private String temp2;  
  10.    private String weather;  
  11.     private String ptime;  
  12.     public String getCity() {  
  13.         return city;  
  14.     }  
  15.     public void setCity(String city) {  
  16.         this.city = city;  
  17.     }  
  18.     public String getCityid() {  
  19.         return cityid;  
  20.     }  
  21.     public void setCityid(String cityid) {  
  22.         this.cityid = cityid;  
  23.     }  
  24.     public String getTemp1() {  
  25.         return temp1;  
  26.     }  
  27.     public void setTemp1(String temp1) {  
  28.         this.temp1 = temp1;  
  29.     }  
  30.     public String getTemp2() {  
  31.         return temp2;  
  32.     }  
  33.     public void setTemp2(String temp2) {  
  34.         this.temp2 = temp2;  
  35.     }  
  36.     public String getWeather() {  
  37.         return weather;  
  38.     }  
  39.     public void setWeather(String weather) {  
  40.         this.weather = weather;  
  41.     }  
  42.     public String getPtime() {  
  43.         return ptime;  
  44.     }  
  45.     public void setPtime(String ptime) {  
  46.         this.ptime = ptime;  
  47.     }  
  48.     @Override  
  49.     public String toString() {  
  50.         return "WeatherInfo [city=" + city + ", cityid=" + cityid + ", temp1="  
  51.                 + temp1 + ", temp2=" + temp2 + ", weather=" + weather  
  52.                 + ", ptime=" + ptime + "]";  
  53.     }  
  54.   
  55.       
  56. }  

      只要在定义一个weatherinfo类就好了,添加city等等字段到该类里头,并且注意属性的数据类型要一一对应的否则会解析失败的,万事具备,剩下来的就交给Gson吧

  1. public static void handleWeatherResponse(Context context, String response) {  
  2.     try {  
  3.           
  4.         Gson gson = new Gson();  
  5.         Weather weather = gson.fromJson(response, Weather.class);  
  6.       
  7.         Weatherinfo info = weather.getWeatherinfo();  
  8.       
  9.         saveWeatherInfo(context, info);  
  10.     } catch (Exception e) {  
  11.         // TODO: handle exception  
  12.     }  
  13. }  

    看到没有只需要三步就完成了数据的解析,有没有很简单呢!我们只需要通过gson,from()方法就可以把数据内容映射到指定类中!SO,easy! 大家可能注意到在这三步骤结束之后还有一个saveWeatherinfo方法,这个方法用来干嘛的呢!

  1. public static void saveWeatherInfo(Context context, Weatherinfo info) {  
  2.   
  3.     SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日", Locale.CHINA);  
  4.     SharedPreferences.Editor editor = PreferenceManager  
  5.             .getDefaultSharedPreferences(context).edit();  
  6.     editor.putBoolean("city_selected", true);  
  7.     editor.putString("city_name", info.getCity());  
  8.     editor.putString("weather_code", info.getCityid());  
  9.     editor.putString("temp1", info.getTemp1());  
  10.     editor.putString("temp2", info.getTemp2());  
  11.     editor.putString("weather_desp", info.getWeather());  
  12.     editor.putString("publish_time", info.getPtime());  
  13.     LogUtil.i("UTILITY", "----------------->" +  sdf.format(new Date()));  
  14.     editor.putString("current_date", sdf.format(new Date()));  
  15.     editor.commit();  
  16. }  

    这个方法就是我们使用Sharedpreference共享参数存储一下我们当天得到的天气数据,这样用户每次打开就可以直接读取之前得到的数据,在有需要的时候再通过网络获取即时的天气数据就好了,editor.put方法还不能直接存储类,只能存储基本的数据类型,我们这里就只能一个个put啦!

    好的,这一节课的内容就讲到这里,也希望大家能继续支持该系列的博文,你们的支持是我写下去的最大动力!今天的GSON解析数据的内容就到此结束,下一篇博文也会很快跟大家见面的。

  下面是该应用的Git开源地址,https://github.com/melhc/SimpleWeather

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多