Gson是Google的Java Json處理工具包。它提供了簡單的API,使得將JSON數據轉換成Java對象(POJO)成為一件簡單的事情。在這篇文章中,我們將使用Gson來解析一個天氣JSON字符串。
{"weather":[ {"city":"北京", "temperature":"12℃", "weather":"晴"}, {"city":"上海", "temperature":"20℃", "weather":"多云"}, {"city":"廣州", "temperature":"25℃", "weather":"陰"}]}
首先,我們需要創建一個Java類來裝載JSON數據。在這個例子中,我們創建一個Weather類,具有城市名,溫度和天氣三個屬性。
public class Weather { private String city; private String temperature; private String weather; // Getter and Setter methods }
下一步是將JSON字符串解析為Weather對象的List。我們可以使用Gson來做到這一點。首先,我們需要獲取JSON字符串。在這個例子中,我們可以直接將JSON字符串硬編碼到Java代碼中。在實際應用中,我們將從網絡或本地文件系統等外部源獲取JSON字符串。
String json = "{\"weather\":[\n" + " {\"city\":\"北京\",\n" + " \"temperature\":\"12℃\",\n" + " \"weather\":\"晴\"},\n" + " {\"city\":\"上海\",\n" + " \"temperature\":\"20℃\",\n" + " \"weather\":\"多云\"},\n" + " {\"city\":\"廣州\",\n" + " \"temperature\":\"25℃\",\n" + " \"weather\":\"陰\"}]}\n";
然后,我們可以使用Gson將JSON字符串解析為Java對象。在這里,我們將使用fromJson()方法將JSON字符串重構為Weather對象的list。我們需要提供一個TypeToken以告訴Gson我們期望的對象類型。
Type listType = new TypeToken<List<Weather>>(){}.getType(); List<Weather> weatherList = new Gson().fromJson(json, listType);
我們現在已經成功將JSON字符串轉換為Java對象并將它們放入一個List中。
最后,我們可以遍歷Weather對象列表并顯示每個城市的天氣情況。
for (Weather weather : weatherList) { System.out.println(weather.getCity() + ": " + weather.getTemperature() + ", " + weather.getWeather()); }
這里是完整的例子代碼:
public class GsonWeatherExample { public static void main(String[] args) { String json = "{\"weather\":[\n" + " {\"city\":\"北京\",\n" + " \"temperature\":\"12℃\",\n" + " \"weather\":\"晴\"},\n" + " {\"city\":\"上海\",\n" + " \"temperature\":\"20℃\",\n" + " \"weather\":\"多云\"},\n" + " {\"city\":\"廣州\",\n" + " \"temperature\":\"25℃\",\n" + " \"weather\":\"陰\"}]}\n"; Type listType = new TypeToken<List<Weather>>(){}.getType(); List<Weather> weatherList = new Gson().fromJson(json, listType); for (Weather weather : weatherList) { System.out.println(weather.getCity() + ": " + weather.getTemperature() + ", " + weather.getWeather()); } } } class Weather { private String city; private String temperature; private String weather; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getTemperature() { return temperature; } public void setTemperature(String temperature) { this.temperature = temperature; } public String getWeather() { return weather; } public void setWeather(String weather) { this.weather = weather; } }
在這篇文章中,我們已經看到了如何使用Gson解析JSON字符串并將其轉換為Java對象。