您的位置:首页 > Web前端 > JavaScript

使用Gson转化天气预报Json

2015-08-07 17:56 459 查看
国家气象局提供的天气预报接口主要有三个,分别是:
http://www.weather.com.cn/data/sk/101010100.html

http://www.weather.com.cn/data/cityinfo/101010100.html
http://m.weather.com.cn/data/101010100.html

访问http://www.weather.com.cn/data/sk/101010100.html得到如下天气预报的Json

{
"weatherinfo": {
"city": "北京",
"cityid": "101010100",
"temp": "9",
"WD": "西南风",
"WS": "2级",
"SD": "24%",
"WSE": "2",
"time": "10:30",
"isRadar": "1",
"Radar": "JC_RADAR_AZ9010_JB",
"njd": "暂无实况",
"qy": "1015"
}
}

北京地区的预报区域代码为:
101010100=北京

101010200=海淀

101010300=朝阳

101010400=顺义

101010500=怀柔

101010600=通州

101010700=昌平

101010800=延庆

101010900=丰台

101011000=石景山

101011100=大兴

101011200=房山

101011300=密云

101011400=门头沟

101011500=平谷

101011600=八达岭

101011700=佛爷顶

101011800=汤河口

101011900=密云上甸子

101012000=斋堂

101012100=霞云岭

我们先定义天气信息的实体类Weatherinfo public class Weatherinfo {

private String city;
private String cityid;
private String temp;
private String WD;
private String WS;
private String SD;
private String WSE;
private String time;
private String isRadar;
private String njd;
private String qy;

public Weatherinfo(String city, String cityid, String temp, String wD,
String wS, String sD, String wSE, String time, String isRadar,
String njd, String qy) {
super();
this.city = city;
this.cityid = cityid;
this.temp = temp;
WD = wD;
WS = wS;
SD = sD;
WSE = wSE;
this.time = time;
this.isRadar = isRadar;
this.njd = njd;
this.qy = qy;
}

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 getTemp() {
return temp;
}

public void setTemp(String temp) {
this.temp = temp;
}

public String getWD() {
return WD;
}

public void setWD(String wD) {
WD = wD;
}

public String getWS() {
return WS;
}

public void setWS(String wS) {
WS = wS;
}

public String getSD() {
return SD;
}

public void setSD(String sD) {
SD = sD;
}

public String getWSE() {
return WSE;
}

public void setWSE(String wSE) {
WSE = wSE;
}

public String getTime() {
return time;
}

public void setTime(String time) {
this.time = time;
}

public String getIsRadar() {
return isRadar;
}

public void setIsRadar(String isRadar) {
this.isRadar = isRadar;
}

public String getNjd() {
return njd;
}

public void setNjd(String njd) {
this.njd = njd;
}

public String getQy() {
return qy;
}

public void setQy(String qy) {
this.qy = qy;
}
}
把Weatherinfo类加到Weather

public class Weather {

private Weatherinfo weatherinfo;

public Weatherinfo getWeatherinfo() {
return weatherinfo;
}

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

使用Gson把json字符串转化为实体
String jsonString = HttpResonse; //返回的天气预报字符串
Gson gson = new Gson();
Weather weather = gson.fromJson(jsonString, Weather.Class);

System.out.print(weather.getWeatherinfo().getCity());
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: