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 :)
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 callinggetAtPath
, I callgetAsString
method.and this is the result:
You can parse the entire stream, and then pull out what you need. Here's an example of parsing it:
Reading it, you have to navigate your way through the table, something like this:
Here's an example from one of my programs using this library:
I make heavy use out of the following to get it right:
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.
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.