簡體   English   中英

Java從URL NullPointerException解析JSON

[英]Java parse JSON from URL NullPointerException

我正在嘗試從以下API解析JSON: https//opentdb.com/api.php?amount = 1

但是當我試圖獲取問題值時,我收到以下錯誤:

Exception in thread "main" java.lang.NullPointerException

我用這個代碼:

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

}

希望有人能告訴我我做錯了什么。

提前致謝!

當我看到你試圖解釋的JSON時,我得到:

{
    "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"]
        }
    ]
}

此JSON不包含根成員"question" 這使得rootobj.get("question")返回null ,因此在其上調用getAsString會拋出NullPointerException

因此,不必使用rootobj.get("question") ,而是必須遍歷層次結構: "results" - >第一個數組成員 - > "question"

rootobj.getAsJsonArray("result").getAsJsonObject(0).get("question")

JSON沒有直接的“問題”字段。 call question = rootobj.get("result").get(0).get("question").getAsString(); 代替

試試這個吧

question = rootobj.getAsJsonArray(“results”)。get(0).getAsJsonObject()。get(“question”)。getAsString();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM