Hacktoberfest 2026:維護者為十月標記出來的 issue,仍然開放、適合新手。 瀏覽 Hacktoberfest issue

NullPointerException in JSONObject(JSONObject, String...) and JSONObject(Object, String...) when names is null

未關閉 適合新手
#1,096 1 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

評估

難度
2/5
預估耗時
1-3 小時
新手友好度
76/100
Issue 類型
缺陷
描述清晰度
描述清楚
活躍度
活躍
技術堆疊
java
領域
backend

研究方向

閱讀 src/main/java/org/json/JSONObject.java 中受影響的兩個建構子,查看 issue 連結所指向的行。檢查它們明確呼叫的 this(...) 如何處理值為 null 的 names 陣列,接著執行或新增針對兩個建構子多載的測試。只有在為 null 選定一致的行為、於 Javadoc 中記錄該行為,並針對兩個建構子完成驗證後,才算完成。

由索引模型根據 Issue 內容生成。

描述

Awaiting further input from submitter

https://github.com/stleary/JSON-java/blob/69383f746d971fd26bb4fe21524295dc385d233f/src/main/java/org/json/JSONObject.java#L183

Description

Both "subset" constructors dereference names.length in their explicit constructor call (this(names.length)) before any validation, so passing a null array throws a raw NullPointerException instead of a meaningful error (or being treated as "no names").

Affected constructors:

  • JSONObject(JSONObject jo, String... names) - JSONObject.java:183
  • JSONObject(Object object, String... names) - JSONObject.java:491

Because the dereference happens inside this(...), it cannot be guarded with a null check or try/catch within the constructor body. The try/catch inside the loop of the first constructor does not help either, since the NPE is thrown before the loop is reached.

Steps to reproduce
JSONObject jo = new JSONObject().put("a", 1);

new JSONObject(jo, (String[]) null);                 // NPE at JSONObject.java:183
new JSONObject(new Object(), (String[]) null);       // NPE at JSONObject.

This can happen in practice when the array comes from a variable or a meth returns null (an omitted varargs argument is an empty array, but an explicit null is passed through as null).

Actual behavior

java.lang.NullPointerException: Cannot read the array length because "name at org.json.JSONObject.<init>(JSONObject.java:183)

Expected behavior

One of the following, applied consistently and documented in the Javadoc:

1. Treat null like an empty array and return an empty JSONObject, or
2. Throw an explicit NullPointerException / IllegalArgumentException with message (e.g. "names must not be null").

A possible minimal fix is to avoid dereferencing names in the this(...) call, e.g.:

this(names == null ? 0 : names.length);
if (names == null) {
    return;
}

Environment

- org.json:json: 20260814 (also present in earlier versions, e.g. 20250517
- Java: OpenJDK 21.0.8
- OS: Linux
主要語言
Java
星號
4.7k
分支
2.6k
平均合併
4 天 17 小時
30 天內合併 PR
7

環境準備

  • 沒有 Dockerfile 或 Docker Compose 檔案
  • 沒有 Pull Request 範本
  • 閱讀貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

stleary/JSON-java 的其他 Issue

查看 stleary/JSON-java 的全部 Issue

相似的 Issue

更多 Java Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。