json是在互联网上使用比较广、且比较轻量的一个数据格式。现在很多的开放平台都会用到这种格式做为返回的数据格式、比如新浪、腾讯的微博开放平台,都可以用这种数据格式来进行二次开发,Json使用很方便、我们可以写一个对应的类来解析这个数据。Google为了方便我们使用json开发了一个Gson包。我们只要导入这个包就可以很简单的解析和封装Json数据。
我们对中国天气Api返回的数据做一个简单的示例:
解析地址:http://www.weather.com.cn/data/cityinfo/101010100.html
json数据:{"weatherinfo":{"city":"北京","cityid":"101010100","temp1":"22℃","temp2":"9℃","weather":"晴","img1":"d0.gif","img2":"n0.gif","ptime":"11:00"}}
分析这个数据可以看出这个包含两个对象.外层一个属性
建立两个类Weather、Weatherinfo
package com.he.data; public class Weather { private Weatherinfo weatherinfo; public Weatherinfo getWeatherinfo() { return weatherinfo; } public void setWeatherinfo(Weatherinfo weatherinfo) { this.weatherinfo = weatherinfo; } }
package com.he.data; public class Weatherinfo { private String city; private String cityid; private String temp1; private String temp2; private String weather; private String img1; private String img2; 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 getImg1() { return img1; } public void setImg1(String img1) { this.img1 = img1; } public String getImg2() { return img2; } public void setImg2(String img2) { this.img2 = img2; } 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 + ", img1=" + img1 + ", img2=" + img2 + ", ptime=" + ptime + "]"; } }
完成这两个对应类就可以直接套用解析了:
package com.he; import java.util.ArrayList; import java.util.List; import com.google.gson.Gson; import com.he.data.Person; import com.he.data.Weather; import com.he.data.Weatherinfo; public class testGson { public void gsonWeather(String str){ Gson gson=new Gson(); Weather weather=gson.fromJson(str, new Weather().getClass());//解析数据类 System.out.println(weather.getWeatherinfo()); System.out.println(gson.toJson(weather));//把对象变成json对象 } public static void main(String[] args) { testGson test=new testGson(); String str="{\"weatherinfo\":{\"city\":\"北京\",\"cityid\":\"101010100\",\"temp1\":\"22℃\",\"temp2\":\"9℃\",\"weather\":\"晴\",\"img1\":\"d0.gif\",\"img2\":\"n0.gif\",\"ptime\":\"11:00\"}}"; test.gsonWeather(str); } }
输出结果:
Weatherinfo [city=北京, cityid=101010100, temp1=22℃, temp2=9℃, weather=晴, img1=d0.gif, img2=n0.gif, ptime=11:00]
{"weatherinfo":{"city":"北京","cityid":"101010100","temp1":"22℃","temp2":"9℃","weather":"晴","img1":"d0.gif","img2":"n0.gif","ptime":"11:00"}}