您的位置:首页 > 移动开发 > Android开发

一起来开发Android的天气软件(四)——使用Gson解析数据

2015-12-27 11:14 525 查看
离上一篇文章过去才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),比方"首都:北京"。它的规格呢也是非常easy固定的。

(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数据?

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

/**
* 解析server返回的JSON数据,并将解析出的数据存储到本地。
*/
public static void handleWeatherResponse(Context context, String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject weatherInfo = jsonObject.getJSONObject("weatherinfo");
String cityName = weatherInfo.getString("city");
String weatherCode = weatherInfo.getString("cityid");
String temp1 = weatherInfo.getString("temp1");
String temp2 = weatherInfo.getString("temp2");
String weatherDesp = weatherInfo.getString("weather");
String publishTime = weatherInfo.getString("ptime");
saveWeatherInfo(context, cityName, weatherCode, temp1, temp2,
weatherDesp, publishTime);
} catch (JSONException e) {
e.printStackTrace();
}
}


将server返回的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类。

package com.melhc.model;

public class Weather {
private Weatherinfo weatherinfo;

public Weatherinfo getWeatherinfo() {
return weatherinfo;
}

public void setWeatherInfo(Weatherinfo weatherinfo) {
this.weatherinfo = weatherinfo;
}
}


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

package com.melhc.model;

public class Weatherinfo {
private String city;
private String cityid;
private String temp1;
private String temp2;
private String weather;
private String ptime;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCityid() {
return cityid;
}
public void setCityid(String cityid) {
this.cityid = cityid;
}
public String getTemp1() {
return temp1;
}
public void setTemp1(String temp1) {
this.temp1 = temp1;
}
public String getTemp2() {
return temp2;
}
public void setTemp2(String temp2) {
this.temp2 = temp2;
}
public String getWeather() {
return weather;
}
public void setWeather(String weather) {
this.weather = weather;
}
public String getPtime() {
return ptime;
}
public void setPtime(String ptime) {
this.ptime = ptime;
}
@Override
public String toString() {
return "WeatherInfo [city=" + city + ", cityid=" + cityid + ", temp1="
+ temp1 + ", temp2=" + temp2 + ", weather=" + weather
+ ", ptime=" + ptime + "]";
}

}


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

public static void handleWeatherResponse(Context context, String response) {
try {

Gson gson = new Gson();
Weather weather = gson.fromJson(response, Weather.class);

Weatherinfo info = weather.getWeatherinfo();

saveWeatherInfo(context, info);
} catch (Exception e) {
// TODO: handle exception
}
}


看到没有仅仅须要三步就完毕了数据的解析。有没有非常easy呢!

我们仅仅须要通过gson,from()方法就能够把数据内容映射到指定类中!SO,easy! 大家可能注意到在这三步骤结束之后另一个saveWeatherinfo方法。这种方法用来干嘛的呢!

public static void saveWeatherInfo(Context context, Weatherinfo info) {

SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日", Locale.CHINA);
SharedPreferences.Editor editor = PreferenceManager
.getDefaultSharedPreferences(context).edit();
editor.putBoolean("city_selected", true);
editor.putString("city_name", info.getCity());
editor.putString("weather_code", info.getCityid());
editor.putString("temp1", info.getTemp1());
editor.putString("temp2", info.getTemp2());
editor.putString("weather_desp", info.getWeather());
editor.putString("publish_time", info.getPtime());
LogUtil.i("UTILITY", "----------------->" +  sdf.format(new Date()));
editor.putString("current_date", sdf.format(new Date()));
editor.commit();
}


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

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

以下是该应用的Git开源地址。https://github.com/melhc/SimpleWeather 2014博客之星请支持一下啊。http://vote.blog.csdn.net/blogstar2014/details?

username=u013900875#content
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: