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"}}