Java JSON with GSON

為{幸葍}努か 提交于 2019-12-23 03:54:12

问题


Here's the problem, I'm using a weather APi from Wunderground and am having trouble using GSON to fetch the weather.

import java.net.*;
import java.io.*;
import com.google.gson.*;

public class URLReader {

    public static URL link;

    public static void main(String[] args) {
        try{
            open();
            read();
        }catch(IOException e){}
    }

    public static void open(){
        try{
            link = new URL("http://api.wunderground.com/api/54f05b23fd8fd4b0/geolookup/conditions/forecast/q/US/CO/Denver.json");
        }catch(MalformedURLException e){}
    }

    public static void read() throws IOException{
        Gson gson = new Gson();

        // Code to get variables like humidity, chance of rain, ect...
    }
} 

That is as far as I got, so can someone please help me to get this thing working. I need to be able to parse specific variables not just the entire JSON file.

I used a buffered reader but it read the entire JSON file.

Thanks in advance, I'm a beginner so go easy and explain things very straightforward :)


回答1:


You can parse the entire stream, and then pull out what you need. Here's an example of parsing it:

    String url=getUrl();
    JSONObject jsonObject = new JSONObject();
    StringBuilder stringBuilder=new StringBuilder();
    try 
    {
        HttpGet httpGet = new HttpGet(url);
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }

        jsonObject = new JSONObject(stringBuilder.toString());

    } catch (JSONException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
    } catch (IOException e) {    }

Reading it, you have to navigate your way through the table, something like this:

jsonObject.getJSONObject("Results");

Here's an example from one of my programs using this library:

int statusCode=jobj.getJSONObject("info").getInt("statuscode");

I make heavy use out of the following to get it right:

jsonObject.names();

That will give you the name of all of the keys. From there, you have to figure out if it's an array, an object, or a primitive type. It takes me a bit to get it right, but once you've done it once, it's done forever, hopefully. Take a look at the Android documents on their JSON library.




回答2:


GSON can parse a JSON tree into a Java object, an instance of a Java class. So, if you want to use GSON for this case, you have to create class(es) and annotate them with the relevant field names of the JSON structure. GSON has a very extensive and easy-to-read documentation, please check it out. However with this kinda complicated tree, i do not recommend to map it into Java objects. If you want just some data, drop GSON and navigate the tree manually as PearsonArtPhoto suggested.




回答3:


You can use JsonParser. This is an example based on your url that you can immediately copy, paste and run.

I added an utility method that allows you to get element from the generated JsonElement tree using something like a path. Your JSON is, indeed, almost a tree of objects and values (except for the forecast part).

Pay attention that a JsonElement can be "cast" again as an object, array or base value as your needs. This is why after calling getAtPath, I call getAsString method.

package stackoverflow.questions.q19966672;

import java.io.*;
import java.net.*;
import java.nio.charset.Charset;

import com.google.gson.*;

public class Q19966672 {

        private static String readAll(Reader rd) throws IOException {

        BufferedReader reader = new BufferedReader(rd);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }

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

    public static void main(String[] args) {
        String url = "http://api.wunderground.com/api/54f05b23fd8fd4b0/geolookup/conditions/forecast/q/US/CO/Denver.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("In " + getAtPath(je, "current_observation/display_location/city").getAsString() + " is " + getAtPath(je, "current_observation/weather").getAsString());

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

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

}

and this is the result:

In Denver is Mostly Cloudy


来源:https://stackoverflow.com/questions/19966672/java-json-with-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!