Skip to content

Commit

Permalink
fix(stleary#887): complete strictMode for JSONArray
Browse files Browse the repository at this point in the history
  • Loading branch information
rikkarth committed Apr 14, 2024
1 parent d02ac0f commit fe597d2
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/main/java/org/json/JSONArray.java
Expand Up @@ -144,6 +144,42 @@ public JSONArray(JSONTokener x, JSONParserConfiguration jsonParserConfiguration)
}
}
}

if (jsonParserConfiguration.isStrictMode()) {
validateInput(x);
}
}

/**
* Checks if Array adheres to strict mode guidelines, if not, throws JSONException providing back the input in the
* error message.
*
* @param x tokener used to examine input.
* @throws JSONException if input is not compliant with strict mode guidelines;
*/
private void validateInput(JSONTokener x) {
char nextChar = x.getPrevious();

boolean isEndOfArray = nextChar == ']';
boolean nextCharacterIsNotEoF = x.nextClean() != 0;

if (isEndOfArray && nextCharacterIsNotEoF) {
String completeInput = collectCompleteInput(x);
throw new JSONException("Provided Array is not compliant with strict mode guidelines: " + completeInput);
}
}

private String collectCompleteInput(JSONTokener x) {
String nonCompliantStringAfterArray = collectNonCompliantStringAfterArray(x);
return myArrayList + nonCompliantStringAfterArray;
}

private String collectNonCompliantStringAfterArray(JSONTokener x) {
StringBuilder sb = new StringBuilder().append(x.getPrevious());
while(x.nextClean() != 0){
sb.append(x.getPrevious());
}
return sb.toString();
}

/**
Expand Down
19 changes: 19 additions & 0 deletions src/test/java/org/json/junit/JSONParserConfigurationTest.java
Expand Up @@ -46,6 +46,16 @@ public void givenInvalidInputArrays_testStrictModeTrue_shouldThrowJsonException(
() -> new JSONArray(testCase, jsonParserConfiguration)));
}

@Test
public void givenValidDoubleArray_testStrictModeTrue_shouldNotThrowJsonException() {
JSONParserConfiguration jsonParserConfiguration = new JSONParserConfiguration()
.withStrictMode(true);

String testCase = "[[\"c\"],[\"a\"]]";

new JSONArray(testCase, jsonParserConfiguration);
}

@Test
public void givenCompliantJSONArrayFile_testStrictModeTrue_shouldNotThrowAnyException() throws IOException {
try (Stream<String> lines = Files.lines(Paths.get("src/test/resources/compliantJsonArray.json"))) {
Expand Down Expand Up @@ -208,6 +218,15 @@ public void verifyMaxDepthThenDuplicateKey() {
*/
private List<String> getNonCompliantJSONList() {
return Arrays.asList(
"[]asdf",
"[]]",
"[]}",
"[][",
"[]{",
"[],",
"[]:",
"[],[",
"[],{",
"[1,2];[3,4]",
"[test]",
"[{'testSingleQuote': 'testSingleQuote'}]",
Expand Down

0 comments on commit fe597d2

Please sign in to comment.