Java解析来自URL NullPointerException的JSON
我试图从以下API解析JSON: 但当我试图获取问题值时,我得到以下错误:Java解析来自URL NullPointerException的JSON,java,json,parsing,nullpointerexception,Java,Json,Parsing,Nullpointerexception,我试图从以下API解析JSON: 但当我试图获取问题值时,我得到以下错误: 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"; //ju
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没有直接的“问题”字段。
调用
question=rootobj.get(“结果”).get(0.get(“问题”).getAsString()代码>相反,当我看到您试图解释的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(“问题”)
返回null
,因此对其调用getAsString
会抛出NullPointerException
因此,您需要遍历层次结构,而不是rootobj.get(“问题”)
,即“结果”
->第一个数组成员->“问题”
:
试试这个
question=rootobj.getAsJsonArray(“结果”).get(0.getAsJsonObject().get(“问题”).getAsString() NullPointerException是哪一行?你试过调试这个程序吗?它是针对第10行的:“question=rootobj.get(“question”).getAsString();”所以rootobj.get(“question”)可能返回null,将这一行分成两行,嗯,刚刚试过你的代码片段,但现在是说“无法解析方法‘get(int)”,没错,你正在使用Gson解析器,它有不同的语法。看起来@Daniel Przybylowski的语法很适合你。
rootobj.getAsJsonArray("result").getAsJsonObject(0).get("question")