Skip to content

Commit 4a23fd8

Browse files
authored
Merge pull request #1061 from stleary/restore-lenient-jsonarray
restore-lenient-jsonarray allow consecutive commas and insert null
2 parents 33a4698 + ad26e94 commit 4a23fd8

2 files changed

Lines changed: 22 additions & 4 deletions

File tree

‎src/main/java/org/json/JSONArray.java‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -131,9 +131,9 @@ public JSONArray(JSONTokener x, JSONParserConfiguration jsonParserConfiguration)
131131
* @param x A JSONTokener instance from which the JSONArray is constructed.
132132
* @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser.
133133
* @param isInitial Boolean indicating position of char
134-
* @return
134+
* @return true if a syntax error has occurred, otherwise false
135135
*/
136-
private static boolean checkForSyntaxError(JSONTokener x, JSONParserConfiguration jsonParserConfiguration, boolean isInitial) {
136+
private boolean checkForSyntaxError(JSONTokener x, JSONParserConfiguration jsonParserConfiguration, boolean isInitial) {
137137
char nextChar;
138138
switch (x.nextClean()) {
139139
case 0:
@@ -153,11 +153,11 @@ private static boolean checkForSyntaxError(JSONTokener x, JSONParserConfiguratio
153153
return true;
154154
}
155155
if (nextChar == ',') {
156-
// consecutive commas are not allowed in strict mode
156+
// Consecutive commas are not allowed in strict mode.
157+
// Otherwise, the tokener is backed up, and a null object is inserted by the calling code.
157158
if (jsonParserConfiguration.isStrictMode()) {
158159
throw x.syntaxError("Strict mode error: Expected a valid array element");
159160
}
160-
return true;
161161
}
162162
x.back();
163163
break;

‎src/test/java/org/json/junit/JSONArrayTest.java‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1548,4 +1548,22 @@ public static ArrayList<Object> buildNestedArray(int maxDepth) {
15481548
nestedArray.add(buildNestedArray(maxDepth - 1));
15491549
return nestedArray;
15501550
}
1551+
1552+
@Test
1553+
public void TestLenientCommas() {
1554+
String str = "[1,,3]";
1555+
1556+
// Test should fail if default strictMode is true, pass with an extra null entry if false
1557+
JSONParserConfiguration jsonParserConfiguration = new JSONParserConfiguration();
1558+
if (jsonParserConfiguration.isStrictMode()) {
1559+
try {
1560+
new JSONArray(str);
1561+
fail("Expected to throw exception due to invalid string");
1562+
} catch (JSONException e) { /* no action is needed here */ }
1563+
} else {
1564+
JSONArray jsonArray = new JSONArray(str);
1565+
assertEquals("JSONArray in non-strictMode should contain a null entry",
1566+
"[1,null,3]", jsonArray.toString());
1567+
}
1568+
}
15511569
}

0 commit comments

Comments
 (0)