Gson在类中获取一个json变量

时间:2019-03-12 23:55:14

标签: java json gson

我正在制作一个天气应用程序,以了解如何在Java中使用Gson和Web api,这是我当前的代码:

public class Weather 
{
    public static void main(String[] args) throws Exception
    {
        URL ipStacks = new URL("http://api.ipstack.com/check?access_key=(my api key)");
        BufferedReader reader = new BufferedReader(
        new InputStreamReader(ipStacks.openStream()));

        String inputLine = reader.readLine();
        String json = inputLine;


        Gson gson = new Gson();
        LocationData location = gson.fromJson(json, LocationData.class);
        System.out.println(location.ip);
        System.out.println(location.latitude);
        System.out.println(location.longitude);

        String darkSkyBase = "https://api.darksky.net/forecast/(my api key)/";
        URL darkSky = new URL(darkSkyBase+location.latitude+","+location.longitude);
        BufferedReader reader2 = new BufferedReader(
        new InputStreamReader(darkSky.openStream()));

        inputLine = reader2.readLine();
        WeatherData weather = gson.fromJson(inputLine, WeatherData.class);
        System.out.println(weather.currently);
    }
}

class LocationData
{
    String ip;
    String latitude;
    String longitude;
}

class WeatherData
{
    String currently;
}

我收到此错误:

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 81 path $.currently
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226)
    at com.google.gson.Gson.fromJson(Gson.java:927)
    at com.google.gson.Gson.fromJson(Gson.java:892)
    at com.google.gson.Gson.fromJson(Gson.java:841)
    at com.google.gson.Gson.fromJson(Gson.java:813)
    at com.thomasbriggs.json.App.main(App.java:37)
Caused by: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 81 path $.currently
    at com.google.gson.stream.JsonReader.nextString(JsonReader.java:825)
    at com.google.gson.internal.bind.TypeAdapters$16.read(TypeAdapters.java:402)
    at com.google.gson.internal.bind.TypeAdapters$16.read(TypeAdapters.java:390)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:131)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:222)
    ... 5 more

我正在猜测,因为使用darksky api,当前是另一个json列表,但是我如何告诉Gson期望一个json列表?

我遇到麻烦的JSON字符串如下所示:

{
          "latitude": 42.3601,
          "longitude": -71.0589,
          "timezone": "America/New_York",
          "currently": {
              "time": 1509993277,
              "summary": "Drizzle",
              "icon": "rain",
              "nearestStormDistance": 0,
              "precipIntensity": 0.0089,
              "precipIntensityError": 0.0046,
              "precipProbability": 0.9,
              "precipType": "rain",
              "temperature": 66.1,
              "apparentTemperature": 66.31,
              "dewPoint": 60.77,
              "humidity": 0.83,
              "pressure": 1010.34,
              "windSpeed": 5.59,
              "windGust": 12.03,
              "windBearing": 246,
              "cloudCover": 0.7,
              "uvIndex": 1,
              "visibility": 9.84,
              "ozone": 267.44
          },
          "minutely": {
              "summary": "Light rain stopping in 13 min., starting again 30 min. later.",
              "icon": "rain",
              "data": [{
                  "time": 1509993240,
                  "precipIntensity": 0.007,
                  "precipIntensityError": 0.004,
                  "precipProbability": 0.84,
                  "precipType": "rain"
              },
            ...
            ]
          },
          "hourly": {
              "summary": "Rain starting later this afternoon, continuing until this evening.",
              "icon": "rain",
              "data": [{
                  "time": 1509991200,
                  "summary": "Mostly Cloudy",
                  "icon": "partly-cloudy-day",
                  "precipIntensity": 0.0007,
                  "precipProbability": 0.1,
                  "precipType": "rain",
                  "temperature": 65.76,
                  "apparentTemperature": 66.01,
                  "dewPoint": 60.99,
                  "humidity": 0.85,
                  "pressure": 1010.57,
                  "windSpeed": 4.23,
                  "windGust": 9.52,
                  "windBearing": 230,
                  "cloudCover": 0.62,
                  "uvIndex": 1,
                  "visibility": 9.32,
                  "ozone": 268.95
              },
            ...
            ]
          },
         "daily": {
              "summary": "Mixed precipitation throughout the week, with temperatures falling to 39°F on Saturday.",
              "icon": "rain",
              "data": [{
                  "time": 1509944400,
                  "summary": "Rain starting in the afternoon, continuing until evening.",
                  "icon": "rain",
                  "sunriseTime": 1509967519,
                  "sunsetTime": 1510003982,
                  "moonPhase": 0.59,
                  "precipIntensity": 0.0088,
                  "precipIntensityMax": 0.0725,
                  "precipIntensityMaxTime": 1510002000,
                  "precipProbability": 0.73,
                  "precipType": "rain",
                  "temperatureHigh": 66.35,
                  "temperatureHighTime": 1509994800,
                  "temperatureLow": 41.28,
                  "temperatureLowTime": 1510056000,
                  "apparentTemperatureHigh": 66.53,
                  "apparentTemperatureHighTime": 1509994800,
                  "apparentTemperatureLow": 35.74,
                  "apparentTemperatureLowTime": 1510056000,
                  "dewPoint": 57.66,
                  "humidity": 0.86,
                  "pressure": 1012.93,
                  "windSpeed": 3.22,
                  "windGust": 26.32,
                  "windGustTime": 1510023600,
                  "windBearing": 270,
                  "cloudCover": 0.8,
                  "uvIndex": 2,
                  "uvIndexTime": 1509987600,
                  "visibility": 10,
                  "ozone": 269.45,
                  "temperatureMin": 52.08,
                  "temperatureMinTime": 1510027200,
                  "temperatureMax": 66.35,
                  "temperatureMaxTime": 1509994800,
                  "apparentTemperatureMin": 52.08,
                  "apparentTemperatureMinTime": 1510027200,
                  "apparentTemperatureMax": 66.53,
                  "apparentTemperatureMaxTime": 1509994800
              },
            ...
            ]
          },
          "alerts": [
          {
            "title": "Flood Watch for Mason, WA",
            "time": 1509993360,
            "expires": 1510036680,
            "description": "...FLOOD WATCH REMAINS IN EFFECT THROUGH LATE MONDAY NIGHT...\nTHE FLOOD WATCH CONTINUES FOR\n* A PORTION OF NORTHWEST WASHINGTON...INCLUDING THE FOLLOWING\nCOUNTY...MASON.\n* THROUGH LATE FRIDAY NIGHT\n* A STRONG WARM FRONT WILL BRING HEAVY RAIN TO THE OLYMPICS\nTONIGHT THROUGH THURSDAY NIGHT. THE HEAVY RAIN WILL PUSH THE\nSKOKOMISH RIVER ABOVE FLOOD STAGE TODAY...AND MAJOR FLOODING IS\nPOSSIBLE.\n* A FLOOD WARNING IS IN EFFECT FOR THE SKOKOMISH RIVER. THE FLOOD\nWATCH REMAINS IN EFFECT FOR MASON COUNTY FOR THE POSSIBILITY OF\nAREAL FLOODING ASSOCIATED WITH A MAJOR FLOOD.\n",
            "uri": "http://alerts.weather.gov/cap/wwacapget.php?x=WA1255E4DB8494.FloodWatch.1255E4DCE35CWA.SEWFFASEW.38e78ec64613478bb70fc6ed9c87f6e6"
          },
          ...
          ],
          {
            "flags": {
              "units": "us",
              ...
            }
          }

如果您有任何疑问,请帮忙。

2 个答案:

答案 0 :(得分:0)

我正在检查JSON,看来您正在获得经度和纬度的双精度值:

"latitude": 42.3601,
"longitude": -71.0589,

但是您正在尝试将它们保存在字符串中

class LocationData
{
    String ip;
    String latitude;
    String longitude;
}

将变量更改为两倍,然后重试。

答案 1 :(得分:0)

currently是一个对象,而您的类型是String。如果您不想为currently创建结构,则将其声明为地图Map<String, Object> currently-GSON会将所有键值对放在此处