Skip to content

Commit 631c21e

Browse files
committed
Try and fix backslash escaping. Throw syntax exception on invalid json sooner
1 parent d9da808 commit 631c21e

File tree

2 files changed

+14
-9
lines changed

2 files changed

+14
-9
lines changed

src/main/java/org/codehaus/jettison/json/JSONObject.java

+7-7
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,8 @@ public JSONObject(JSONTokener x) throws JSONException {
220220
throw x.syntaxError("A JSONObject text must end with '}'");
221221
case '}':
222222
return;
223+
case '{':
224+
throw x.syntaxError("Expected a key");
223225
default:
224226
x.back();
225227
key = x.nextValue().toString();
@@ -1041,15 +1043,13 @@ public static String quote(String string, boolean escapeForwardSlashAlways) {
10411043
c = string.charAt(i);
10421044
switch (c) {
10431045
case '\\':
1044-
// Escape a backslash, but only if it isn't already escaped
1045-
if (i == len - 1 || string.charAt(i + 1) != '\\') {
1046-
sb.append('\\');
1047-
}
1048-
sb.append(c);
1046+
sb.append("\\\\");
1047+
//if (i < (len - 1) && string.charAt(i+1) == '\\') {
1048+
// i++;
1049+
//}
10491050
break;
10501051
case '"':
1051-
sb.append('\\');
1052-
sb.append(c);
1052+
sb.append("\\\"");
10531053
break;
10541054
case '/':
10551055
if (escapeForwardSlashAlways || i > 0 && string.charAt(i - 1) == '<') {

src/test/java/org/codehaus/jettison/json/JSONObjectTest.java

+7-2
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,11 @@ public void testMissingIsNull() throws Exception {
8787
public void testSlashEscapingTurnedOnByDefault() throws Exception {
8888
JSONObject obj = new JSONObject();
8989
obj.put("key", "http://example.com/foo");
90-
assertEquals(obj.toString(), "{\"key\":\"http:\\/\\/example.com\\/foo\"}");
90+
assertEquals("{\"key\":\"http:\\/\\/example.com\\/foo\"}", obj.toString());
91+
92+
obj = new JSONObject();
93+
obj.put("key", "\\\\");
94+
assertEquals("{\"key\":\"\\\\\\\\\"}", obj.toString());
9195
}
9296

9397
public void testForwardSlashEscapingModifiedfBySetter() throws Exception {
@@ -183,13 +187,14 @@ public void testFuzzerTestCase() throws Exception, JSONException {
183187
fail("Failure expected");
184188
} catch (JSONException ex) {
185189
// expected
190+
assertTrue(ex.getMessage().contains("Expected a key"));
186191
}
187192
}
188193

189194
public void testFuzzerTestCase2() throws Exception {
190195
StringBuilder sb = new StringBuilder();
191196
for (int i = 0; i < 100000; i++) {
192-
sb.append("{");
197+
sb.append("{\"key\":");
193198
}
194199
try {
195200
new JSONObject(sb.toString());

0 commit comments

Comments
 (0)