From c073157a61e89c5c6f0769df1ca94e4fb8e9758b Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Mon, 15 Jun 2026 16:43:46 -0500 Subject: [PATCH] restore-lenient-jsonarray initial commit --- src/main/java/org/json/JSONArray.java | 8 ++++---- .../java/org/json/junit/JSONArrayTest.java | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/json/JSONArray.java b/src/main/java/org/json/JSONArray.java index 2a3c553..d1dcf5c 100644 --- a/src/main/java/org/json/JSONArray.java +++ b/src/main/java/org/json/JSONArray.java @@ -131,9 +131,9 @@ public class JSONArray implements Iterable { * @param x A JSONTokener instance from which the JSONArray is constructed. * @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser. * @param isInitial Boolean indicating position of char - * @return + * @return true if a syntax error has occurred, otherwise false */ - private static boolean checkForSyntaxError(JSONTokener x, JSONParserConfiguration jsonParserConfiguration, boolean isInitial) { + private boolean checkForSyntaxError(JSONTokener x, JSONParserConfiguration jsonParserConfiguration, boolean isInitial) { char nextChar; switch (x.nextClean()) { case 0: @@ -153,11 +153,11 @@ public class JSONArray implements Iterable { return true; } if (nextChar == ',') { - // consecutive commas are not allowed in strict mode + // Consecutive commas are not allowed in strict mode. + // Otherwise, the tokener is backed up, and a null object is inserted by the calling code. if (jsonParserConfiguration.isStrictMode()) { throw x.syntaxError("Strict mode error: Expected a valid array element"); } - return true; } x.back(); break; diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index 011c250..3761dd9 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -1548,4 +1548,22 @@ public class JSONArrayTest { nestedArray.add(buildNestedArray(maxDepth - 1)); return nestedArray; } + + @Test + public void TestLenientCommas() { + String str = "[1,,3]"; + + // Test should fail if default strictMode is true, pass with an extra null entry if false + JSONParserConfiguration jsonParserConfiguration = new JSONParserConfiguration(); + if (jsonParserConfiguration.isStrictMode()) { + try { + JSONArray jsonArray = new JSONArray(str); + fail("Expected to throw exception due to invalid string"); + } catch (JSONException e) { } + } else { + JSONArray jsonArray = new JSONArray(str); + assertEquals("JSONArray in non-strictMode should contain a null entry", + "[1,null,3]", jsonArray.toString()); + } + } }