简体   繁体   English

使用 Gson 从 Json 中提取值

[英]Extract value from Json using Gson

I am trying to extract values from JSON from the URL provided below using GSON java library: http://api.wunderground.com/api/b28d047ca410515a/forecast/q/-33.912,151.013.json我正在尝试使用 GSON java 库从下面提供的 URL 中提取 JSON 值: http ://api.wunderground.com/api/b28d047ca410515a/forecast/q/-33.912,151.013.json

I have successfully used the code provided below to extract data from URL below: http://api.wunderground.com/api/b28d047ca410515a/conditions/q/-33.912,151.013.json我已成功使用下面提供的代码从下面的 URL 中提取数据: http : //api.wunderground.com/api/b28d047ca410515a/conditions/q/-33.912,151.013.json

Code:代码:

   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();
                }
            } 

However I am getting exception trying to extract from url2 as per code below , it seems to be a more complicated json to get values from, any help please?但是,我在尝试按照下面的代码从 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 code: 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;
    }

The problem you are facing is because there is an issue with the getAtPath implementation.您面临的问题是因为getAtPath实现存在问题。

[{"date":{"epoch":"1459152000"... represents a JSONArray which the method is trying to access as JSONObject. [{"date":{"epoch":"1459152000"...表示方法试图作为 JSONObject 访问的 JSONArray。 Hence the IllegalStateException .因此, IllegalStateException

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

convenience method to get this element as a JsonObject.将此元素作为 JsonObject 获取的便捷方法。 If the element is of some other type, a IllegalStateException will result.如果元素是其他类型,则会导致 IllegalStateException。 Hence it is best to use this method after ensuring that this element is of the desired type by calling isJsonObject() first.因此,最好先调用 isJsonObject() 确保此元素为所需类型后使用此方法。

You can update and use something like below, as of now it returns only the first element.您可以更新和使用类似下面的内容,到目前为止它只返回第一个元素。

    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;
    }

这应该有效:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM