I'm trying to parse the JSON from the following API: https://opentdb.com/api.php?amount=1
but when I'm trying to get the question value, I get the following error:
Exception in thread "main" java.lang.NullPointerException
I use this code:
public static void main(String[] args) throws IOException {
String question;
String sURL = "https://opentdb.com/api.php?amount=1"; //just a string
// Connect to the URL using java's native library
URL url = new URL(sURL);
URLConnection request = url.openConnection();
request.connect();
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object.
question = rootobj.get("question").getAsString(); //grab the question
}
Hope someone can tell me what I am doing wrong.
Thanks in advance!