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 摘要。