java - Gson获取类中的json变量

标签 java json gson

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

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

任何帮助都会很棒,如果您有任何问题,请询问。

最佳答案

currently是一个对象,而您的类型是 String。如果您不想为 currently 创建结构然后将其声明为 map Map<String, Object> currently - GSON 将把所有键值对放在这里

关于java - Gson获取类中的json变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55132393/

相关文章:

java - 用于调试的 ant 任务不起作用 : Cause: the name is undefined

c++ - 使用 boost ptree 将 std::list 序列化为 json

java - 使用 Gson 反序列化可通过接口(interface)引用访问的通用类实例

java - ContextRefreshed 后 Spring WebApp 中 ScheduledFutureTask 中的 RejectedExecutionException

java - 如何在 JNI 中处理类结构体 jobject

python - 如何将 Twitter json 对象加载到 python 中

java - 如何处理基于模板的解析器中的冗余标记名称

android - 使用 Retrofit 将动态 JSON 解析为 POJO

java - 编译错误 - 在 Redhat "Openshift"应用程序中找不到包 com.google.gson

java - 服务器验证失败后如何在jsp页面上重新填充表单字段