如何使用GSON反序列化

时间:2013-02-16 19:35:36

标签: java json gson

{
    "response": {
        "version": "0.1",
        "termsofService": "http://www.wunderground.com/weather/api/d/terms.html",
        "features": {
            "geolookup": 1,
            "conditions": 1,
            "forecast": 1
        }
    },
    "location": {
        "type": "INTLCITY",
        "country": "IN",
        "country_iso3166": "IN",
        "country_name": "India",
        "state": "",
        "city": "Mumbai",
        "tz_short": "IST",
        "tz_long": "Asia/Kolkata",
        "lat": "19.12000084",
        "lon": "72.84999847",
        "zip": "00000",
        "magic": "1",
        "wmo": "43003",
        "l": "/q/zmw:00000.1.43003",
        "requesturl": "global/stations/43003.html",
        "wuiurl": "http://www.wunderground.com/global/stations/43003.html",
        "nearby_weather_stations": {
            "airport": {
                "station": [
                    {
                        "city": "Mumbai / Santacruz",
                        "state": "",
                        "country": "India",
                        "icao": "VABB",
                        "lat": "19.11666679",
                        "lon": "72.84999847"
                    },
                    {
                        "city": "Mumbai",
                        "state": "",
                        "country": "IN",
                        "icao": "VABB",
                        "lat": "19.12000084",
                        "lon": "72.84999847"
                    }
                ]
            },
            "pws": {
                "station": []
            }
        }
    },
    "current_observation": {
        "image": {
            "url": "http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png",
            "title": "Weather Underground",
            "link": "http://www.wunderground.com"
        },
        "display_location": {
            "full": "Mumbai, India",
            "city": "Mumbai",
            "state": "",
            "state_name": "India",
            "country": "IN",
            "country_iso3166": "IN",
            "zip": "00000",
            "latitude": "19.12000084",
            "longitude": "72.84999847",
            "elevation": "14.00000000"
        },
        "observation_location": {
            "full": "Mumbai, ",
            "city": "Mumbai",
            "state": "",
            "country": "IN",
            "country_iso3166": "IN",
            "latitude": "19.12000084",
            "longitude": "72.84999847",
            "elevation": "46 ft"
        },
        "estimated": {},
        "station_id": "VABB",
        "observation_time": "Last Updated on February 16, 11:40 PM IST",
        "observation_time_rfc822": "Sat, 16 Feb 2013 23:40:00 +0530",
        "observation_epoch": "1361038200",
        "local_time_rfc822": "Sun, 17 Feb 2013 00:16:13 +0530",
        "local_epoch": "1361040373",
        "local_tz_short": "IST",
        "local_tz_long": "Asia/Kolkata",
        "local_tz_offset": "+0530",
        "weather": "Smoke",
        "temperature_string": "73 F (23 C)",
        "temp_f": 73,
        "temp_c": 23,
        "relative_humidity": "50%",
        "wind_string": "From the WNW at 5 MPH",
        "wind_dir": "WNW",
        "wind_degrees": 300,
        "wind_mph": 5,
        "wind_gust_mph": 0,
        "wind_kph": 7,
        "wind_gust_kph": 0,
        "pressure_mb": "1011",
        "pressure_in": "29.86",
        "pressure_trend": "0",
        "dewpoint_string": "54 F (12 C)",
        "dewpoint_f": 54,
        "dewpoint_c": 12,
        "heat_index_string": "NA",
        "heat_index_f": "NA",
        "heat_index_c": "NA",
        "windchill_string": "NA",
        "windchill_f": "NA",
        "windchill_c": "NA",
        "feelslike_string": "73 F (23 C)",
        "feelslike_f": "73",
        "feelslike_c": "23",
        "visibility_mi": "2.5",
        "visibility_km": "4.0",
        "solarradiation": "",
        "UV": "-1",
        "precip_1hr_string": "-9999.00 in (-9999.00 mm)",
        "precip_1hr_in": "-9999.00",
        "precip_1hr_metric": "-9999.00",
        "precip_today_string": "0.00 in (0.0 mm)",
        "precip_today_in": "0.00",
        "precip_today_metric": "0.0",
        "icon": "hazy",
        "icon_url": "http://icons-ak.wxug.com/i/c/k/nt_hazy.gif",
        "forecast_url": "http://www.wunderground.com/global/stations/43003.html",
        "history_url": "http://www.wunderground.com/history/airport/VABB/2013/2/16/DailyHistory.html",
        "ob_url": "http://www.wunderground.com/cgi-bin/findweather/getForecast?query=19.12000084,72.84999847"
    },
    "forecast": {
        "txt_forecast": {
            "date": "5:30 AM IST",
            "forecastday": [
                {
                    "period": 0,
                    "icon": "clear",
                    "icon_url": "http://icons-ak.wxug.com/i/c/k/clear.gif",
                    "title": "Sunday",
                    "fcttext": "Clear. High of 82F. Winds from the NE at 5 to 15 mph shifting to the WNW in the afternoon.",
                    "fcttext_metric": "Clear. High of 28C. Winds from the NE at 5 to 20 km/h shifting to the WNW in the afternoon.",
                    "pop": "0"
                },
                {
                    "period": 1,
                    "icon": "clear",
                    "icon_url": "http://icons-ak.wxug.com/i/c/k/clear.gif",
                    "title": "Sunday Night",
                    "fcttext": "Partly cloudy. Low of 66F. Winds from the North at 5 to 10 mph.",
                    "fcttext_metric": "Partly cloudy. Low of 19C. Winds from the North at 10 to 15 km/h.",
                    "pop": "0"
                },
                {
                    "period": 2,
                    "icon": "partlycloudy",
                    "icon_url": "http://icons-ak.wxug.com/i/c/k/partlycloudy.gif",
                    "title": "Monday",
                    "fcttext": "Clear. High of 88F. Winds from the NNE at 5 to 15 mph shifting to the WNW in the afternoon.",
                    "fcttext_metric": "Clear. High of 31C. Breezy. Winds from the NNE at 10 to 20 km/h shifting to the WNW in the afternoon.",
                    "pop": "0"
                },
                {
                    "period": 3,
                    "icon": "clear",
                    "icon_url": "http://icons-ak.wxug.com/i/c/k/clear.gif",
                    "title": "Monday Night",
                    "fcttext": "Clear. Low of 64F. Winds from the NNE at 5 to 10 mph.",
                    "fcttext_metric": "Clear. Low of 18C. Winds from the NNE at 10 to 15 km/h.",
                    "pop": "0"
                },
                {
                    "period": 4,
                    "icon": "clear",
                    "icon_url": "http://icons-ak.wxug.com/i/c/k/clear.gif",
                    "title": "Tuesday",
                    "fcttext": "Clear. High of 90F. Winds from the NNE at 5 to 10 mph shifting to the WNW in the afternoon.",
                    "fcttext_metric": "Clear. High of 32C. Winds from the NNE at 5 to 20 km/h shifting to the WNW in the afternoon.",
                    "pop": "0"
                },
                {
                    "period": 5,
                    "icon": "clear",
                    "icon_url": "http://icons-ak.wxug.com/i/c/k/clear.gif",
                    "title": "Tuesday Night",
                    "fcttext": "Clear. Low of 64F. Winds from the North at 5 to 10 mph.",
                    "fcttext_metric": "Clear. Low of 18C. Winds from the North at 5 to 15 km/h.",
                    "pop": "0"
                },
                {
                    "period": 6,
                    "icon": "clear",
                    "icon_url": "http://icons-ak.wxug.com/i/c/k/clear.gif",
                    "title": "Wednesday",
                    "fcttext": "Clear. High of 90F. Winds from the North at 5 to 10 mph shifting to the WNW in the afternoon.",
                    "fcttext_metric": "Clear. High of 32C. Winds from the North at 5 to 20 km/h shifting to the WNW in the afternoon.",
                    "pop": "0"
                },
                {
                    "period": 7,
                    "icon": "clear",
                    "icon_url": "http://icons-ak.wxug.com/i/c/k/clear.gif",
                    "title": "Wednesday Night",
                    "fcttext": "Clear. Low of 70F. Winds from the North at 5 to 10 mph.",
                    "fcttext_metric": "Clear. Low of 21C. Winds from the North at 10 to 15 km/h.",
                    "pop": "0"
                }
            ]
        },
        "simpleforecast": {
            "forecastday": [
                {
                    "date": {
                        "epoch": "1361124000",
                        "pretty": "11:30 PM IST on February 17, 2013",
                        "day": 17,
                        "month": 2,
                        "year": 2013,
                        "yday": 47,
                        "hour": 23,
                        "min": "30",
                        "sec": 0,
                        "isdst": "0",
                        "monthname": "February",
                        "weekday_short": "Sun",
                        "weekday": "Sunday",
                        "ampm": "PM",
                        "tz_short": "IST",
                        "tz_long": "Asia/Kolkata"
                    },
                    "period": 1,
                    "high": {
                        "fahrenheit": "82",
                        "celsius": "28"
                    },
                    "low": {
                        "fahrenheit": "66",
                        "celsius": "19"
                    },
                    "conditions": "Clear",
                    "icon": "clear",
                    "icon_url": "http://icons-ak.wxug.com/i/c/k/clear.gif",
                    "skyicon": "sunny",
                    "pop": 0,
                    "qpf_allday": {
                        "in": 0,
                        "mm": 0
                    },
                    "qpf_day": {
                        "in": 0,
                        "mm": 0
                    },
                    "qpf_night": {
                        "in": 0,
                        "mm": 0
                    },
                    "snow_allday": {
                        "in": 0,
                        "cm": 0
                    },
                    "snow_day": {
                        "in": 0,
                        "cm": 0
                    },
                    "snow_night": {
                        "in": 0,
                        "cm": 0
                    },
                    "maxwind": {
                        "mph": 12,
                        "kph": 19,
                        "dir": "WNW",
                        "degrees": 300
                    },
                    "avewind": {
                        "mph": 8,
                        "kph": 13,
                        "dir": "SW",
                        "degrees": 232
                    },
                    "avehumidity": 54,
                    "maxhumidity": 66,
                    "minhumidity": 38
                },
                {
                    "date": {
                        "epoch": "1361210400",
                        "pretty": "11:30 PM IST on February 18, 2013",
                        "day": 18,
                        "month": 2,
                        "year": 2013,
                        "yday": 48,
                        "hour": 23,
                        "min": "30",
                        "sec": 0,
                        "isdst": "0",
                        "monthname": "February",
                        "weekday_short": "Mon",
                        "weekday": "Monday",
                        "ampm": "PM",
                        "tz_short": "IST",
                        "tz_long": "Asia/Kolkata"
                    },
                    "period": 2,
                    "high": {
                        "fahrenheit": "88",
                        "celsius": "31"
                    },
                    "low": {
                        "fahrenheit": "64",
                        "celsius": "18"
                    },
                    "conditions": "Partly Cloudy",
                    "icon": "partlycloudy",
                    "icon_url": "http://icons-ak.wxug.com/i/c/k/partlycloudy.gif",
                    "skyicon": "sunny",
                    "pop": 0,
                    "qpf_allday": {
                        "in": 0,
                        "mm": 0
                    },
                    "qpf_day": {
                        "in": 0,
                        "mm": 0
                    },
                    "qpf_night": {
                        "in": 0,
                        "mm": 0
                    },
                    "snow_allday": {
                        "in": 0,
                        "cm": 0
                    },
                    "snow_day": {
                        "in": 0,
                        "cm": 0
                    },
                    "snow_night": {
                        "in": 0,
                        "cm": 0
                    },
                    "maxwind": {
                        "mph": 11,
                        "kph": 18,
                        "dir": "WNW",
                        "degrees": 301
                    },
                    "avewind": {
                        "mph": 8,
                        "kph": 13,
                        "dir": "SW",
                        "degrees": 231
                    },
                    "avehumidity": 45,
                    "maxhumidity": 62,
                    "minhumidity": 27
                },
                {
                    "date": {
                        "epoch": "1361296800",
                        "pretty": "11:30 PM IST on February 19, 2013",
                        "day": 19,
                        "month": 2,
                        "year": 2013,
                        "yday": 49,
                        "hour": 23,
                        "min": "30",
                        "sec": 0,
                        "isdst": "0",
                        "monthname": "February",
                        "weekday_short": "Tue",
                        "weekday": "Tuesday",
                        "ampm": "PM",
                        "tz_short": "IST",
                        "tz_long": "Asia/Kolkata"
                    },
                    "period": 3,
                    "high": {
                        "fahrenheit": "90",
                        "celsius": "32"
                    },
                    "low": {
                        "fahrenheit": "64",
                        "celsius": "18"
                    },
                    "conditions": "Clear",
                    "icon": "clear",
                    "icon_url": "http://icons-ak.wxug.com/i/c/k/clear.gif",
                    "skyicon": "sunny",
                    "pop": 0,
                    "qpf_allday": {
                        "in": 0,
                        "mm": 0
                    },
                    "qpf_day": {
                        "in": 0,
                        "mm": 0
                    },
                    "qpf_night": {
                        "in": 0,
                        "mm": 0
                    },
                    "snow_allday": {
                        "in": 0,
                        "cm": 0
                    },
                    "snow_day": {
                        "in": 0,
                        "cm": 0
                    },
                    "snow_night": {
                        "in": 0,
                        "cm": 0
                    },
                    "maxwind": {
                        "mph": 10,
                        "kph": 16,
                        "dir": "NW",
                        "degrees": 310
                    },
                    "avewind": {
                        "mph": 8,
                        "kph": 13,
                        "dir": "West",
                        "degrees": 277
                    },
                    "avehumidity": 43,
                    "maxhumidity": 47,
                    "minhumidity": 28
                },
                {
                    "date": {
                        "epoch": "1361383200",
                        "pretty": "11:30 PM IST on February 20, 2013",
                        "day": 20,
                        "month": 2,
                        "year": 2013,
                        "yday": 50,
                        "hour": 23,
                        "min": "30",
                        "sec": 0,
                        "isdst": "0",
                        "monthname": "February",
                        "weekday_short": "Wed",
                        "weekday": "Wednesday",
                        "ampm": "PM",
                        "tz_short": "IST",
                        "tz_long": "Asia/Kolkata"
                    },
                    "period": 4,
                    "high": {
                        "fahrenheit": "90",
                        "celsius": "32"
                    },
                    "low": {
                        "fahrenheit": "70",
                        "celsius": "21"
                    },
                    "conditions": "Clear",
                    "icon": "clear",
                    "icon_url": "http://icons-ak.wxug.com/i/c/k/clear.gif",
                    "skyicon": "sunny",
                    "pop": 0,
                    "qpf_allday": {
                        "in": 0,
                        "mm": 0
                    },
                    "qpf_day": {
                        "in": 0,
                        "mm": 0
                    },
                    "qpf_night": {
                        "in": 0,
                        "mm": 0
                    },
                    "snow_allday": {
                        "in": 0,
                        "cm": 0
                    },
                    "snow_day": {
                        "in": 0,
                        "cm": 0
                    },
                    "snow_night": {
                        "in": 0,
                        "cm": 0
                    },
                    "maxwind": {
                        "mph": 10,
                        "kph": 16,
                        "dir": "WNW",
                        "degrees": 301
                    },
                    "avewind": {
                        "mph": 8,
                        "kph": 13,
                        "dir": "West",
                        "degrees": 267
                    },
                    "avehumidity": 44,
                    "maxhumidity": 51,
                    "minhumidity": 30
                }
            ]
        }
    }
}   



为了使用GSON反序列化它,我创建了类(不详尽),如下所示:

import com.google.gson.annotations.*;
public class Response {
    @SerializedName("version")
    String version;
    @SerializedName("termsOfService")
    String termsOfService;
    @SerializedName("features")
    Features features;
}

import com.google.gson.annotations.*;
public class Features {
    @SerializedName("geolookup")
    String geolookup;
    @SerializedName("conditions")
    String conditions;
    @SerializedName("forecast")
    String forecast;
}   

import com.google.gson.annotations.*;
public class Location {
    @SerializedName("type")
    String type;
    @SerializedName("country")
    String country;
    @SerializedName("country_iso3166")
    String country_iso3166;
    @SerializedName("country_name")
    String country_name;
    @SerializedName("state")
    String state;
    @SerializedName("city")
    String city;
    @SerializedName("tz_short")
    String tz_short;
    @SerializedName("tz_long")
    String tz_long;
    @SerializedName("lat")
    String lat;
    @SerializedName("lon")
    String lon;
    @SerializedName("zip")
    String zip;
    @SerializedName("magic")
    String magic;
    @SerializedName("wmo")
    String wmo;
    @SerializedName("l")
    String l;
    @SerializedName("requesturl")
    String requesturl;
    @SerializedName("wuiurl")
    String wuiurl;
    @SerializedName("nearby_weather_stations")
    NearbyWeatherStations nearby_weather_stations;

}

import com.google.gson.annotations.*;
public class NearbyWeatherStations {
    @SerializedName("airport")
    Airport airport;
    @SerializedName("pws")
    PWS pws;
}

依此类推

问题

我做得对吗? GSON需要getter / setter方法吗?我的意思是,如果我覆盖某个类的toString方法以获取我想要的格式的数据并避免编写getter / setter那么有效吗?

1 个答案:

答案 0 :(得分:3)

  1. 一般来说:是的。创建DTO类可以为您提供类型安全性,但您可以使用弱Map<String, Object>
  2. 如果目标JSON属性名称与相应的Java字段匹配,则可以省略@SerializedName。但是,如果您按照驼峰案例进行字段名称会更好: @SerializedName("nearby_weather_stations") NearbyWeatherStations nearbyWeatherStations;
  3. GSON既不考虑吸气剂也不考虑吸气剂。以下是GSON仅使用字段的原因:https://stackoverflow.com/a/6203975/166589
  4. 请不要使用toString()来序列化对象。 (如果将转换器/(反)序列化器分开则会更好 - 它可以为您提供更大的灵活性而不会更改原始对象,并允许您以轻量级方式使用toString()结果,例如在手表窗口中调试。)

  5. UPD1:

    您错过了一个类来访问给定JSON的根属性:

    public static class Wrapper { /* or whatever you can call it */
    
        private Response response;
        private Location location;
        ...
    
    }
    
    Wrapper wrapper = gson.fromJson(json, Wrapper.class);