使用 Gson 从 Json 中提取值

Extract value from Json using Gson

我正在尝试使用 GSON java 库从下面提供的 URL 中提取 JSON 的值: http://api.wunderground.com/api/b28d047ca410515a/forecast/q/-33.912,151.013.json

我已成功使用下面提供的代码从下面的 URL 中提取数据: http://api.wunderground.com/api/b28d047ca410515a/conditions/q/-33.912,151.013.json

代码:

   String url = "http://api.wunderground.com/api/b28d047ca410515a/conditions/q/-33.912,151.013.json";
   String url2 = "http://api.wunderground.com/api/b28d047ca410515a/forecast/q/-33.912,151.013.json";

            InputStream is = null;
            try {
                is = new URL(url).openStream();
                BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
                String jsonText = readAll(rd);

                JsonElement je = new JsonParser().parse(jsonText);

                System.out.println("Current Temperature:" + getAtPath(je, "current_observation/temp_c").getAsString() );


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();

            } finally {
                try {
                    if (is != null)
                        is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } 

但是我在尝试按照下面的代码从 url2 中提取时遇到异常,从中获取值似乎更复杂 json,有什么帮助吗?

// below code not working

            weather_icon_url = getAtPath(je, "current_observation/icon_url").getAsString();

            is = new URL(url2).openStream();
            BufferedReader rd2 = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText2 = readAll(rd2);

            JsonElement je2 = new JsonParser().parse(jsonText2);

            System.out.println("max Temperature:" + getAtPath(je2, "forecast/simpleforecast/forecastday/high/celsius").getAsString() );

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } 

getAtPath 代码:

private static JsonElement getAtPath(JsonElement e, String path) {
        JsonElement current = e;
        String ss[] = path.split("/");
        for (int i = 0; i < ss.length; i++) {
            current = current.getAsJsonObject().get(ss[i]);
        }
        return current;
    }

这应该有效:

System.out.println("max Temperature:" + getAtPath(je2, "forecast/simpleforecast/forecastday/high/celsius").getAsString() );

您遇到的问题是因为 getAtPath 实施存在问题。

[{"date":{"epoch":"1459152000"... 表示一个 JSONArray,该方法试图将其作为 JSONObject 进行访问。因此 IllegalStateException.

JsonObject com.google.gson.JsonElement.getAsJsonObject()

convenience method to get this element as a JsonObject. If the element is of some other type, a IllegalStateException will result. Hence it is best to use this method after ensuring that this element is of the desired type by calling isJsonObject() first.

您可以更新和使用如下所示的内容,截至目前它 returns 只有第一个元素。

    private static JsonElement getAtPath(JsonElement e, String path) {
        JsonElement current = e;
        String ss[] = path.split("/");
        for (int i = 0; i < ss.length; i++) {
            if(current instanceof JsonObject){
                current = current.getAsJsonObject().get(ss[i]);
            } else if(current instanceof JsonArray){
                JsonElement jsonElement = current.getAsJsonArray().get(0);
                current = jsonElement.getAsJsonObject().get(ss[i]);
            }
        }
        return current;
    }