Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java parse JSON from URL NullPointerException

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!

like image 849
kristoffer Avatar asked Jun 21 '26 10:06

kristoffer


1 Answers

When I look at the JSON you are trying to interpret, I get:

{
    "response_code": 0,
    "results":[
        {
            "category": "Entertainment: Board Games",
            "type": "multiple",
            "difficulty": "medium",
            "question": "Who is the main character in the VHS tape included in the board game Nightmare?",
            "correct_answer": "The Gatekeeper",
            "incorrect_answers":["The Kryptkeeper","The Monster","The Nightmare"]
        }
    ]
}

This JSON doesn't contain a root member "question". This makes rootobj.get("question") return null, and therefore calling getAsString on it throws the NullPointerException.

So instead of rootobj.get("question"), you would have to walk through the hierarchy: "results" -> first array member -> "question":

rootobj.getAsJsonArray("result").getAsJsonObject(0).get("question")
like image 134
Waggili Avatar answered Jun 24 '26 04:06

Waggili



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!