我正在尝试从以下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
}
希望有人能告诉我自己做错了什么。
提前致谢!
答案 0 :(得分:7)
当我看到你试图解释的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")
答案 1 :(得分:2)
JSON没有直接的问题"领域。
请致电question = rootobj.get("result").get(0).get("question").getAsString();
答案 2 :(得分:2)
试试这个
question = rootobj.getAsJsonArray(“results”)。get(0).getAsJsonObject()。get(“question”)。getAsString();