Java 从 URL NullPointerException 解析 JSON

标签 java json parsing 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" -> 第一个数组成员 -> “问题”:

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

关于Java 从 URL NullPointerException 解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50800983/

相关文章:

java - 检查String是否为java代码

java - 如何从 Amazon elastic map reduce 中的映射器访问文件内容?

android - 如何解析 JsonArray 中的 JsonObject

json - Dart/flutter : build_value vs json_serializable

java - "The left hand side of an assignment must be a variable"由于额外的括号

java - 在 Eclipse 中使用 AST 处理不解析绑定(bind)

FileUploadBean.uploadFile 中的 java.lang.NullPointerException

java - 在 Telegram 中将电话号码交换为用户 ID

ios - 无法使用 afnetworking 注册用户

javascript - 从字符串中解析出一个字符