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

GSON使用实践

2015-11-29 00:21 369 查看
首先,我们以一个雅虎天气的json格式信息作为例子
String url ="https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
他将会返回如下的信息
{
"query": {
"count": 1,
"created": "2015-11-28T16:01:44Z",
"lang": "zh-cn",
"results": {
"channel": {
"title": "Yahoo! Weather - Nome, AK",
"link": "http://us.rd.yahoo.com/dailynews/rss/weather/Nome__AK/*http://weather.yahoo.com/forecast/USAK0170_f.html",
"description": "Yahoo! Weather for Nome, AK",
"language": "en-us",
"lastBuildDate": "Sat, 28 Nov 2015 6:16 am AKST",
"ttl": "60",
"location": {
"city": "Nome",
"country": "United States",
"region": "AK"
},
"units": {
"distance": "mi",
"pressure": "in",
"speed": "mph",
"temperature": "F"
},
"wind": {
"chill": "17",
"direction": "90",
"speed": "22"
},
"atmosphere": {
"humidity": "90",
"pressure": "29.17",
"rising": "1",
"visibility": "9"
},
"astronomy": {
"sunrise": "11:14 am",
"sunset": "4:22 pm"
},
"image": {
"title": "Yahoo! Weather",
"width": "142",
"height": "18",
"link": "http://weather.yahoo.com",
"url": "http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif"
},
"item": {
"title": "Conditions for Nome, AK at 6:16 am AKST",
"lat": "64.5",
"long": "-165.41",
"link": "http://us.rd.yahoo.com/dailynews/rss/weather/Nome__AK/*http://weather.yahoo.com/forecast/USAK0170_f.html",
"pubDate": "Sat, 28 Nov 2015 6:16 am AKST",
"condition": {
"code": "26",
"date": "Sat, 28 Nov 2015 6:16 am AKST",
"temp": "30",
"text": "Cloudy"
},
"description": "\n<img src=\"http://l.yimg.com/a/i/us/we/52/26.gif\"/><br />\n<b>Current Conditions:</b><br />\nCloudy, 30 F<BR />\n<BR /><b>Forecast:</b><BR />\nSat - Snow Showers. High: 32 Low: 26<br />\nSun - Cloudy. High: 27 Low: 23<br />\nMon - Partly Cloudy. High: 24 Low: 14<br />\nTue - Mostly Sunny. High: 17 Low: 7<br />\nWed - Partly Cloudy. High: 10 Low: 4<br />\n<br />\n<a href=\"http://us.rd.yahoo.com/dailynews/rss/weather/Nome__AK/*http://weather.yahoo.com/forecast/USAK0170_f.html\">Full Forecast at Yahoo! Weather</a><BR/><BR/>\n(provided by <a href=\"http://www.weather.com\" >The Weather Channel</a>)<br/>\n",
"forecast": [
{
"code": "14",
"date": "28 Nov 2015",
"day": "Sat",
"high": "32",
"low": "26",
"text": "Snow Showers"
},
{
"code": "26",
"date": "29 Nov 2015",
"day": "Sun",
"high": "27",
"low": "23",
"text": "Cloudy"
},
{
"code": "30",
"date": "30 Nov 2015",
"day": "Mon",
"high": "24",
"low": "14",
"text": "Partly Cloudy"
},
{
"code": "34",
"date": "1 Dec 2015",
"day": "Tue",
"high": "17",
"low": "7",
"text": "Mostly Sunny"
},
{
"code": "30",
"date": "2 Dec 2015",
"day": "Wed",
"high": "10",
"low": "4",
"text": "Partly Cloudy"
}
],
"guid": {
"isPermaLink": "false",
"content": "USAK0170_2015_12_02_7_00_AKST"
}
}
}
}
}
}
我们可以发现,query是root键,里面有很多信息,其中还有以数组形式存在的forecast信息。
现在,就让我们尝试获取预测的天气信息。
gson会将json格式的信息转换成object,但是object的class需要自己定义。
如果遇到小的信息(如forecast),我们还需要定义多个class,用于对应不同的信息。
public class ForecastBean {private String date;private String text;private String temp;private String high;private String low;private String day;public String getTemp() {return temp;}public void setTemp(String temp) {this.temp = temp;}public String getText() {return text;}public void setText(String text) {this.text = text;}public String getDate() {return date;}public void setDate(String date) {this.date = date;}public String getHigh() {return high;}public void setHigh(String high) {this.high = high;}public String getLow() {return low;}public void setLow(String low) {this.low = low;}public String getDay() {return day;}//    public void setDay(String day) {//        this.day = day;//    }}
由于forecastBean是包含在数组里的,为了清晰,我们再定义一个包含forecastBean的arraylist的类——itemBean
itemBean本应有很多属性的,不过由于这里只需要forecast信息,所以我们就忽略了其他属性
最后,定义整个json信息的类
public class ForecastInfoBean {private String description;private String lastBuildDate;private itemBean item;public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}public String getLastBuildDate() {return lastBuildDate;}public void setLastBuildDate(String lastBuildDate) {this.lastBuildDate = lastBuildDate;}public itemBean getItem() {return item;}public void setItem(itemBean item) {this.item = item;}}
如今我们从小到大定义了所有属性,我们在从大到小获取我们想要的信息
我们将api的内容转换成json object
JSONObject jsonObject = new JSONObject(response);
            JSONObject info_object = jsonObject.getJSONObject("query").getJSONObject("results").getJSONObject("channel");ForecastInfoBean forecastInfoBean;forecastInfoBean = gson.fromJson(info_object.toString(), ForecastInfoBean.class);itemBean item = gson.fromJson(info_object.get("item").toString(),itemBean.class);ArrayList<ForecastBean> forecastBeans = item.getForecast();for (ForecastBean forecastBean:forecastBeans){System.out.println(forecastBean.getDate()+"||"+forecastBean.getDay()+"||"+forecastBean.getText());}
我们可以看到,用到的关键函数是gson.fromJson(jsonObject),这样就会返回一个对应的自己定义的class object,并且自定义的属性都会拥有json信息中对应的value。

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