From 90563eb8777e35e0ddf95c7a67a75102d26b04a4 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Mon, 13 Jul 2026 15:33:12 -0500 Subject: [PATCH 01/33] 1063-option-3 parserConfig set max len --- src/main/java/org/json/JSONObject.java | 32 ++++- src/main/java/org/json/JSONTokener.java | 2 +- .../java/org/json/ParserConfiguration.java | 62 ++++++++- src/main/java/org/json/XML.java | 26 +++- .../java/org/json/junit/JSONObjectTest.java | 130 +++++++++++------- 5 files changed, 193 insertions(+), 59 deletions(-) diff --git a/src/main/java/org/json/JSONObject.java b/src/main/java/org/json/JSONObject.java index 2471aa037..cb7d1a7e0 100644 --- a/src/main/java/org/json/JSONObject.java +++ b/src/main/java/org/json/JSONObject.java @@ -2667,16 +2667,33 @@ protected static boolean isDecimalNotation(final String val) { /** * Try to convert a string into a number, boolean, or null. If the string * can't be converted, return the string. + * Warning! stringToValue(String) uses the default max number length. If you want to override it, + * use a suitable initialized JSONParserConfiguration and the method: stringToValue(String, JSONParserConfiguration). * - * @param string - * A String. can not be null. + * @param str A String. can not be null. * @return A simple JSON value. * @throws NullPointerException * Thrown if the string is null. */ // Changes to this method must be copied to the corresponding method in // the XML class to keep full support for Android - public static Object stringToValue(String string) { + public static Object stringToValue(String str) { + return stringToValue(str, new JSONParserConfiguration()); + } + + /** + * Try to convert a string into a number, boolean, or null. If the string + * can't be converted, return the string. + * + * @param string A String. can not be null. + * @param jsonParserConfiguration the parser config + * @return A simple JSON value. If the string represents a number that is too large, + * a string will be returned. + * @throws NullPointerException Thrown if the string is null. + */ + // Changes to this method must be copied to the corresponding method in + // the XML class to keep full support for Android + public static Object stringToValue(String string, JSONParserConfiguration jsonParserConfiguration) { if ("".equals(string)) { return string; } @@ -2700,7 +2717,14 @@ public static Object stringToValue(String string) { char initial = string.charAt(0); if ((initial >= '0' && initial <= '9') || initial == '-') { try { - if (string.length() <= 1000) { + if (jsonParserConfiguration == null) { + jsonParserConfiguration = new JSONParserConfiguration(); + } + // user declines max number checking + if (jsonParserConfiguration.getMaxNumberLength() == JSONParserConfiguration.UNDEFINED_MAXIMUM_NUMBER_LENGTH) { + return stringToNumber(string); + } + if (string.length() <= jsonParserConfiguration.getMaxNumberLength()) { return stringToNumber(string); } } catch (Exception ignore) { diff --git a/src/main/java/org/json/JSONTokener.java b/src/main/java/org/json/JSONTokener.java index 07ff18c99..3726856d3 100644 --- a/src/main/java/org/json/JSONTokener.java +++ b/src/main/java/org/json/JSONTokener.java @@ -513,7 +513,7 @@ Object nextSimpleValue(char c) { jsonParserConfiguration.isStrictMode() && string.endsWith(".")) { throw this.syntaxError(String.format("Strict mode error: Value '%s' ends with dot", string)); } - Object obj = JSONObject.stringToValue(string); + Object obj = JSONObject.stringToValue(string, jsonParserConfiguration); // if obj is a boolean, look at string if (jsonParserConfiguration != null && jsonParserConfiguration.isStrictMode()) { diff --git a/src/main/java/org/json/ParserConfiguration.java b/src/main/java/org/json/ParserConfiguration.java index 06cc44366..df700b355 100644 --- a/src/main/java/org/json/ParserConfiguration.java +++ b/src/main/java/org/json/ParserConfiguration.java @@ -13,11 +13,21 @@ public class ParserConfiguration { */ public static final int UNDEFINED_MAXIMUM_NESTING_DEPTH = -1; + /** + * Used to indicate there's no defined limit to the maximum number length + */ + public static final int UNDEFINED_MAXIMUM_NUMBER_LENGTH = -1; + /** * The default maximum nesting depth when parsing a document. */ public static final int DEFAULT_MAXIMUM_NESTING_DEPTH = 512; + /** + * The default max number length + */ + public static final int DEFAULT_MAX_NUMBER_LENGTH = 1000; + /** * Specifies if values should be kept as strings (true), or if * they should try to be guessed into JSON values (numeric, boolean, string). @@ -29,23 +39,31 @@ public class ParserConfiguration { */ protected int maxNestingDepth; + /** + * The max number of chars for any number. Exceeding this limit will cause the value to be converted to a string + */ + protected int maxNumberLength; + /** * Constructs a new ParserConfiguration with default settings. */ public ParserConfiguration() { this.keepStrings = false; this.maxNestingDepth = DEFAULT_MAXIMUM_NESTING_DEPTH; + this.maxNumberLength = DEFAULT_MAX_NUMBER_LENGTH; } /** - * Constructs a new ParserConfiguration with the specified settings. + * Constructs a new ParserConfiguration with the specified settings. Use the with* methods instead of calling this ctor. * * @param keepStrings A boolean indicating whether to preserve strings during parsing. * @param maxNestingDepth An integer representing the maximum allowed nesting depth. + * @deprecated */ protected ParserConfiguration(final boolean keepStrings, final int maxNestingDepth) { this.keepStrings = keepStrings; this.maxNestingDepth = maxNestingDepth; + this.maxNumberLength = DEFAULT_MAX_NUMBER_LENGTH; } /** @@ -58,10 +76,11 @@ protected ParserConfiguration clone() { // item, a new map instance should be created and if possible each value in the // map should be cloned as well. If the values of the map are known to also // be immutable, then a shallow clone of the map is acceptable. - return new ParserConfiguration( - this.keepStrings, - this.maxNestingDepth - ); + ParserConfiguration parserConfiguration = new ParserConfiguration(); + parserConfiguration.keepStrings = this.keepStrings; + parserConfiguration.maxNestingDepth = this.maxNestingDepth; + parserConfiguration.maxNumberLength = this.maxNumberLength; + return parserConfiguration; } /** @@ -123,4 +142,37 @@ public T withMaxNestingDepth(int maxNestingDepth return newConfig; } + + + /** + * The maximum number length that the parser will allow + * + * @return the maximum number lengtj set for this configuration + */ + public int getMaxNumberLength() { + return maxNumberLength; + } + + /** + * Defines the maximum number length that the parser will allow + * Using any negative value as a parameter is equivalent to setting no limit to the length + * which means any size number is allowed + * + * @param maxNumberLength the maximum number length allowed + * @param the type of the configuration object + * @return The existing configuration will not be modified. A new configuration is returned. + */ + @SuppressWarnings("unchecked") + public T withMaxNumberLength(int maxNumberLength) { + T newConfig = (T) this.clone(); + + if (maxNumberLength > UNDEFINED_MAXIMUM_NUMBER_LENGTH) { + newConfig.maxNumberLength = maxNumberLength; + } else { + newConfig.maxNumberLength = UNDEFINED_MAXIMUM_NUMBER_LENGTH; + } + + return newConfig; + } + } diff --git a/src/main/java/org/json/XML.java b/src/main/java/org/json/XML.java index 716b6d647..195da8d5d 100644 --- a/src/main/java/org/json/XML.java +++ b/src/main/java/org/json/XML.java @@ -617,16 +617,32 @@ public static Object stringToValue(String string, XMLXsiTypeConverter typeCon return stringToValue(string); } + /** + * This method is the same as {@link JSONObject#stringToValue(String)}. + * Warning! stringToValue(String) uses the default max number length. If you want to override it, + * use a suitable initialized XMLParserConfiguration and the method: stringToValue(String, XMLParserConfiguration). + * @param str String to convert + * @return JSON value of this string or the string + */ + // To maintain compatibility with the Android API, this method is a direct copy of + // the one in JSONObject. Changes made here should be reflected there. + // This method should not make calls out of the XML object. + public static Object stringToValue(String str) { + return stringToValue(str, new XMLParserConfiguration()); + } + /** * This method is the same as {@link JSONObject#stringToValue(String)}. * * @param string String to convert - * @return JSON value of this string or the string + * @param xmlParserConfiguration the XML parser config object + * @return JSON value of this string or the string. If the string represents a number that is too large, + * a string will be returned. */ // To maintain compatibility with the Android API, this method is a direct copy of // the one in JSONObject. Changes made here should be reflected there. // This method should not make calls out of the XML object. - public static Object stringToValue(String string) { + public static Object stringToValue(String string, XMLParserConfiguration xmlParserConfiguration) { if ("".equals(string)) { return string; } @@ -650,7 +666,11 @@ public static Object stringToValue(String string) { char initial = string.charAt(0); if ((initial >= '0' && initial <= '9') || initial == '-') { try { - if(string.length() <= 1000) { + // user declines max number checking + if (xmlParserConfiguration.getMaxNumberLength() == JSONParserConfiguration.UNDEFINED_MAXIMUM_NUMBER_LENGTH) { + return stringToNumber(string); + } + if(string.length() <= xmlParserConfiguration.getMaxNumberLength()) { return stringToNumber(string); } } catch (Exception ignore) { diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 6762cf071..4a32b602d 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -67,7 +67,6 @@ import org.json.junit.data.CustomClassH; import org.json.junit.data.CustomClassI; import org.json.junit.data.CustomClassJ; -import org.json.JSONObject; import org.junit.After; import org.junit.Ignore; import org.junit.Test; @@ -3801,33 +3800,84 @@ public void testMaxNumberLength() { sb.append("9999999999"); } - // edge case: JSONObject with number just under the max length limit - String s1Object = "{ \"a\": " + sb + "}"; - JSONObject jsonObject1 = new JSONObject(s1Object); - Object obj1Object = jsonObject1.get("a"); - assertTrue(obj1Object instanceof Number); - assertEquals(1000, obj1Object.toString().length()); - - // edge case: JSONArray with number just under the max length limit - String s1Array = "[" + sb + "]"; - JSONArray jsonArray1 = new JSONArray(s1Array); - Object obj1Array = jsonArray1.get(0); - assertTrue(obj1Array instanceof Number); - assertEquals(1000, obj1Array.toString().length()); - - // edge case: JSONObject with number just over the max length limit - String s2Object = "{ \"a\": " + sb + "9}"; - JSONObject jsonObject2 = new JSONObject(s2Object); - Object obj2Object = jsonObject2.get("a"); - assertTrue(obj2Object instanceof String); - assertEquals(1001, ((String) obj2Object).length()); - - // edge case: JSONArray with number just over the max length limit - String s2Array = "[" + sb + "9]"; - JSONArray jsonArray2 = new JSONArray(s2Array); - Object obj2Array = jsonArray2.get(0); - assertTrue(obj2Array instanceof String); - assertEquals(1001, ((String) obj2Array).length()); + // JSONObject with number just under the max length limit + checkJSONObjectMaxLen(sb.toString(), true, null); + + // JSONArray with number just under the max length limit + checkJSONArrayMaxLen(sb.toString(), true, null); + + // JSONObject with number just over the max length limit + checkJSONObjectMaxLen(sb + "9", false, null); + + // JSONArray with number just over the max length limit + checkJSONArrayMaxLen(sb + "9", false, null); + + // JSONObject with number at config max length limit + checkJSONObjectMaxLen(sb.toString() + sb.toString(), true, new JSONParserConfiguration().withMaxNumberLength(2000)); + + // JSONArray with number at config max length limit + checkJSONArrayMaxLen((sb.toString() + sb), true, new JSONParserConfiguration().withMaxNumberLength(2000)); + + // JSONObject with number just over config max length limit + checkJSONObjectMaxLen(sb.toString() + sb.toString() + "9", false, new JSONParserConfiguration().withMaxNumberLength(2000)); + + // JSONArray with number just over config max length limit + checkJSONArrayMaxLen((sb.toString() + sb + "9"), false, new JSONParserConfiguration().withMaxNumberLength(2000)); + + // JSONObject with large number, no checks + checkJSONObjectMaxLen(sb.toString() + sb.toString() + "9", true, + new JSONParserConfiguration().withMaxNumberLength(JSONParserConfiguration.UNDEFINED_MAXIMUM_NUMBER_LENGTH)); + + // JSONArray with number just over config max length limit + checkJSONArrayMaxLen((sb.toString() + sb + "9"), true, + new JSONParserConfiguration().withMaxNumberLength(JSONParserConfiguration.UNDEFINED_MAXIMUM_NUMBER_LENGTH)); + } + + /** + * Convenience method to check JSONObject for a long number + * @param s string containing the number digits to check + * @param isValid true if number is valid, otherwise false + * @param jsonParserConfiguration the config object + */ + private static void checkJSONObjectMaxLen(String s, boolean isValid, JSONParserConfiguration jsonParserConfiguration) { + String str = "{ \"a\": " + s + "}"; + JSONObject jsonObject; + if (jsonParserConfiguration == null) { + jsonObject = new JSONObject(str); + } else { + jsonObject = new JSONObject(str, jsonParserConfiguration); + } + Object obj = jsonObject.get("a"); + if (isValid) { + assertTrue(obj instanceof Number); + } else { + assertTrue(obj instanceof String); + } + // may not work for scientific notation and BigDecimal + // assertEquals(s.length(), obj.toString().length()); + } + + /** + * Convenience method to check JSONArray for a long number + * @param s string containing the number digits to check + * @param isValid true if number is valid, otherwise false + */ + private static void checkJSONArrayMaxLen(String s, boolean isValid, JSONParserConfiguration jsonParserConfiguration) { + String str = "[" + s + "]"; + JSONArray jsonArray; + if (jsonParserConfiguration == null) { + jsonArray = new JSONArray(str); + } else { + jsonArray = new JSONArray(str, jsonParserConfiguration); + } + Object obj = jsonArray.get(0); + if (isValid) { + assertTrue(obj instanceof Number); + } else { + assertTrue(obj instanceof String); + } + // may not work for scientific notation and BigDecimal + // assertEquals(s.length(), obj.toString().length()); } /** @@ -3843,16 +3893,12 @@ public void testMaxNumberLengthNegativeInteger() { assertEquals(1000, sb.length()); // at max length: parsed as number - JSONObject jo = new JSONObject("{ \"a\": " + sb + "}"); - Object val = jo.get("a"); - assertTrue("Expected Number but got " + val.getClass(), val instanceof Number); + checkJSONObjectMaxLen(sb.toString(), true, null); // over max length: returned as string sb.append("1"); assertEquals(1001, sb.length()); - JSONObject jo2 = new JSONObject("{ \"a\": " + sb + "}"); - Object val2 = jo2.get("a"); - assertTrue("Expected String but got " + val2.getClass(), val2 instanceof String); + checkJSONObjectMaxLen(sb.toString(), false, null); } /** @@ -3873,16 +3919,12 @@ public void testMaxNumberLengthDecimal() { assertEquals(1000, sb.length()); // at max length: parsed as number (BigDecimal) - JSONObject jo = new JSONObject("{ \"a\": " + sb + "}"); - Object val = jo.get("a"); - assertTrue("Expected Number but got " + val.getClass(), val instanceof Number); + checkJSONObjectMaxLen(sb.toString(), true, null); // over max length: returned as string sb.append("3"); assertEquals(1001, sb.length()); - JSONObject jo2 = new JSONObject("{ \"a\": " + sb + "}"); - Object val2 = jo2.get("a"); - assertTrue("Expected String but got " + val2.getClass(), val2 instanceof String); + checkJSONObjectMaxLen(sb.toString(), false, null); } /** @@ -3899,9 +3941,7 @@ public void testMaxNumberLengthScientificNotation() { assertEquals(1000, sb.length()); // at max length: parsed as number - JSONObject jo = new JSONObject("{ \"a\": " + sb + "}"); - Object val = jo.get("a"); - assertTrue("Expected Number but got " + val.getClass(), val instanceof Number); + checkJSONObjectMaxLen(sb.toString(), true, null); // over max length: returned as string sb = new StringBuilder("1."); @@ -3910,9 +3950,7 @@ public void testMaxNumberLengthScientificNotation() { } sb.append("e100"); assertEquals(1001, sb.length()); - JSONObject jo2 = new JSONObject("{ \"a\": " + sb + "}"); - Object val2 = jo2.get("a"); - assertTrue("Expected String but got " + val2.getClass(), val2 instanceof String); + checkJSONObjectMaxLen(sb.toString(), false, null); } /** From fce83c91bb229dde472283dea648a9a8955237fd Mon Sep 17 00:00:00 2001 From: Mirko Swillus Date: Tue, 14 Jul 2026 11:59:27 +0200 Subject: [PATCH 02/33] #1063: bound BigDecimal->BigInteger expansion in objectToBigInteger Completes the CVE-2026-59171 fix started in ab92bb9 / #1065. The 1000-char length guard in stringToValue admits short exponent-notation literals (e.g. 1e100000000, 11 chars) which are stored compactly as BigDecimal and only expand when getBigInteger/optBigInteger calls BigDecimal.toBigInteger(), materialising ~10^8 digits and stalling the thread or throwing OOM. Guard both toBigInteger() sites in objectToBigInteger by rejecting any BigDecimal whose integer part would exceed ParserConfiguration.DEFAULT_MAX_NUMBER_LENGTH decimal digits (precision() - scale(), both O(1) reads). Returns defaultValue on overflow, matching the method's existing behaviour for non-finite and unparseable values. Covers JSONObject.getBigInteger/optBigInteger and JSONArray.getBigInteger/optBigInteger (all delegate to this helper). Adds JSONObjectTest.getBigIntegerHugeExponentReturnsDefault with a 5s timeout so a regression fails fast rather than hanging CI. Co-Authored-By: Claude --- src/main/java/org/json/JSONObject.java | 16 +++++++- .../java/org/json/junit/JSONObjectTest.java | 37 +++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/json/JSONObject.java b/src/main/java/org/json/JSONObject.java index cb7d1a7e0..908cc6996 100644 --- a/src/main/java/org/json/JSONObject.java +++ b/src/main/java/org/json/JSONObject.java @@ -1399,7 +1399,15 @@ static BigInteger objectToBigInteger(Object val, BigInteger defaultValue) { return (BigInteger) val; } if (val instanceof BigDecimal){ - return ((BigDecimal) val).toBigInteger(); + BigDecimal bd = (BigDecimal) val; + // Same ceiling as the parse-time maxNumberLength guard: refuse to + // materialise an integer whose decimal representation would exceed + // DEFAULT_MAX_NUMBER_LENGTH digits. Prevents DoS via short exponent + // literals like 1e100000000 (CVE-2026-59171, see issue #1063). + if ((long) bd.precision() - bd.scale() > ParserConfiguration.DEFAULT_MAX_NUMBER_LENGTH) { + return defaultValue; + } + return bd.toBigInteger(); } if (val instanceof Double || val instanceof Float){ if (!numberIsFinite((Number)val)) { @@ -1422,7 +1430,11 @@ static BigInteger objectToBigInteger(Object val, BigInteger defaultValue) { */ final String valStr = val.toString(); if(isDecimalNotation(valStr)) { - return new BigDecimal(valStr).toBigInteger(); + BigDecimal bd = new BigDecimal(valStr); + if ((long) bd.precision() - bd.scale() > ParserConfiguration.DEFAULT_MAX_NUMBER_LENGTH) { + return defaultValue; + } + return bd.toBigInteger(); } return new BigInteger(valStr); } catch (Exception e) { diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 4a32b602d..a06c3dd44 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1367,6 +1367,43 @@ public void bigNumberOperations() { Util.checkJSONArrayMaps(jsonArray1, jsonObject0.getMapType()); } + /** + * Verifies that getBigInteger / optBigInteger do not attempt to materialise a + * BigInteger whose decimal representation would exceed + * ParserConfiguration.DEFAULT_MAX_NUMBER_LENGTH digits. A short exponent-notation + * literal such as 1e100000000 is stored compactly as a BigDecimal at parse time + * but would otherwise expand to ~100 000 000 digits in BigDecimal.toBigInteger(), + * stalling the thread / OOM (CVE-2026-59171, issue #1063). + */ + @Test(timeout = 5000) + public void getBigIntegerHugeExponentReturnsDefault() { + // BigDecimal path: value arrives via the parser as a BigDecimal + JSONObject jo = new JSONObject("{\"x\":1e100000000}"); + assertTrue("huge-exponent literal parses to BigDecimal", jo.get("x") instanceof BigDecimal); + assertNull("optBigInteger returns default for huge exponent", jo.optBigInteger("x", null)); + try { + jo.getBigInteger("x"); + fail("getBigInteger should throw for huge exponent"); + } catch (JSONException expected) { + } + + // String path: value put() as a String, exercised via objectToBigInteger's + // isDecimalNotation branch + JSONObject jo2 = new JSONObject(); + jo2.put("x", "1e100000000"); + assertNull("optBigInteger returns default for huge-exponent string", jo2.optBigInteger("x", null)); + + // JSONArray accessors delegate to the same helper + JSONArray ja = new JSONArray("[1e100000000]"); + assertTrue("optBigInteger returns default for huge exponent (array)", + BigInteger.ONE.equals(ja.optBigInteger(0, BigInteger.ONE))); + + // Boundary: a value at the limit still converts correctly + JSONObject jo3 = new JSONObject("{\"x\":1e999}"); + assertEquals("1e999 still converts", 0, + jo3.getBigInteger("x").compareTo(BigInteger.TEN.pow(999))); + } + /** * The purpose for the static method getNames() methods are not clear. This * method is not called from within JSON-Java. Most likely uses are to prep From e40d933d50f085c983cce5c377c3cad75216ef6b Mon Sep 17 00:00:00 2001 From: Mirko Swillus Date: Tue, 14 Jul 2026 13:36:46 +0200 Subject: [PATCH 03/33] #1063: add comment to expected-exception catch block (SonarCloud java:S108) Co-Authored-By: Claude --- src/test/java/org/json/junit/JSONObjectTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index a06c3dd44..5ac4643d8 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1385,6 +1385,7 @@ public void getBigIntegerHugeExponentReturnsDefault() { jo.getBigInteger("x"); fail("getBigInteger should throw for huge exponent"); } catch (JSONException expected) { + // expected: integer part exceeds DEFAULT_MAX_NUMBER_LENGTH digits } // String path: value put() as a String, exercised via objectToBigInteger's From 703ac34a55400f9c50889e3d0c778b6d7962e81c Mon Sep 17 00:00:00 2001 From: Mirko Swillus Date: Thu, 16 Jul 2026 11:42:40 +0200 Subject: [PATCH 04/33] #1063: add JSONParserConfiguration overloads for getBigInteger/optBigInteger Per review on #1067: - objectToBigInteger(val, dflt, JSONParserConfiguration) uses cfg.getMaxNumberLength() for the digit-count guard; -1 disables it. Existing 2-arg form delegates with a default config. - New public overloads on JSONObject and JSONArray: getBigInteger(key, cfg) / optBigInteger(key, dflt, cfg). Existing methods delegate with a default config. - objectToBigDecimal left unchanged (no expansion path; agreed on PR). - Tests cover default (1000), raised (2000), lowered (5), disabled (-1), null config, and JSONArray overloads. Co-Authored-By: Claude --- src/main/java/org/json/JSONArray.java | 52 ++++++++++++- src/main/java/org/json/JSONObject.java | 78 +++++++++++++++++-- .../java/org/json/junit/JSONObjectTest.java | 52 +++++++++++++ 3 files changed, 172 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/json/JSONArray.java b/src/main/java/org/json/JSONArray.java index d1dcf5c44..0d7fde9df 100644 --- a/src/main/java/org/json/JSONArray.java +++ b/src/main/java/org/json/JSONArray.java @@ -483,8 +483,29 @@ public BigDecimal getBigDecimal (int index) throws JSONException { * to a BigInteger. */ public BigInteger getBigInteger (int index) throws JSONException { + return this.getBigInteger(index, new JSONParserConfiguration()); + } + + /** + * Get the BigInteger value associated with an index. + * + * @param index + * The index must be between 0 and length() - 1. + * @param jsonParserConfiguration + * A configuration whose {@code maxNumberLength} bounds the number of + * decimal digits in the returned integer. Values exceeding this length + * are treated as unconvertible. Pass a configuration with + * {@link ParserConfiguration#UNDEFINED_MAXIMUM_NUMBER_LENGTH} to disable + * this check. + * @return The value. + * @throws JSONException + * If the key is not found or if the value cannot be converted + * to a BigInteger. + */ + public BigInteger getBigInteger (int index, JSONParserConfiguration jsonParserConfiguration) + throws JSONException { Object object = this.get(index); - BigInteger val = JSONObject.objectToBigInteger(object, null); + BigInteger val = JSONObject.objectToBigInteger(object, null, jsonParserConfiguration); if(val == null) { throw wrongValueFormatException(index, "BigInteger", object, null); } @@ -960,8 +981,8 @@ public > E optEnum(Class clazz, int index, E defaultValue) } /** - * Get the optional BigInteger value associated with an index. The - * defaultValue is returned if there is no value for the index, or if the + * Get the optional BigInteger value associated with an index. The + * defaultValue is returned if there is no value for the index, or if the * value is not a number and cannot be converted to a number. * * @param index @@ -971,8 +992,31 @@ public > E optEnum(Class clazz, int index, E defaultValue) * @return The value. */ public BigInteger optBigInteger(int index, BigInteger defaultValue) { + return this.optBigInteger(index, defaultValue, new JSONParserConfiguration()); + } + + /** + * Get the optional BigInteger value associated with an index. The + * defaultValue is returned if there is no value for the index, or if the + * value is not a number and cannot be converted to a number. + * + * @param index + * The index must be between 0 and length() - 1. + * @param defaultValue + * The default value. + * @param jsonParserConfiguration + * A configuration whose {@code maxNumberLength} bounds the number of + * decimal digits in the returned integer. Values exceeding this length + * are treated as unconvertible and {@code defaultValue} is returned. + * Pass a configuration with + * {@link ParserConfiguration#UNDEFINED_MAXIMUM_NUMBER_LENGTH} to disable + * this check. + * @return The value. + */ + public BigInteger optBigInteger(int index, BigInteger defaultValue, + JSONParserConfiguration jsonParserConfiguration) { Object val = this.opt(index); - return JSONObject.objectToBigInteger(val, defaultValue); + return JSONObject.objectToBigInteger(val, defaultValue, jsonParserConfiguration); } /** diff --git a/src/main/java/org/json/JSONObject.java b/src/main/java/org/json/JSONObject.java index 908cc6996..bf9f92007 100644 --- a/src/main/java/org/json/JSONObject.java +++ b/src/main/java/org/json/JSONObject.java @@ -760,8 +760,29 @@ public boolean getBoolean(String key) throws JSONException { * be converted to BigInteger. */ public BigInteger getBigInteger(String key) throws JSONException { + return this.getBigInteger(key, new JSONParserConfiguration()); + } + + /** + * Get the BigInteger value associated with a key. + * + * @param key + * A key string. + * @param jsonParserConfiguration + * A configuration whose {@code maxNumberLength} bounds the number of + * decimal digits in the returned integer. Values exceeding this length + * are treated as unconvertible. Pass a configuration with + * {@link ParserConfiguration#UNDEFINED_MAXIMUM_NUMBER_LENGTH} to disable + * this check. + * @return The numeric value. + * @throws JSONException + * if the key is not found or if the value cannot + * be converted to BigInteger. + */ + public BigInteger getBigInteger(String key, JSONParserConfiguration jsonParserConfiguration) + throws JSONException { Object object = this.get(key); - BigInteger ret = objectToBigInteger(object, null); + BigInteger ret = objectToBigInteger(object, null, jsonParserConfiguration); if (ret != null) { return ret; } @@ -1381,8 +1402,31 @@ static BigDecimal objectToBigDecimal(Object val, BigDecimal defaultValue, boolea * @return An object which is the value. */ public BigInteger optBigInteger(String key, BigInteger defaultValue) { + return this.optBigInteger(key, defaultValue, new JSONParserConfiguration()); + } + + /** + * Get an optional BigInteger associated with a key, or the defaultValue if + * there is no such key or if its value is not a number. If the value is a + * string, an attempt will be made to evaluate it as a number. + * + * @param key + * A key string. + * @param defaultValue + * The default. + * @param jsonParserConfiguration + * A configuration whose {@code maxNumberLength} bounds the number of + * decimal digits in the returned integer. Values exceeding this length + * are treated as unconvertible and {@code defaultValue} is returned. + * Pass a configuration with + * {@link ParserConfiguration#UNDEFINED_MAXIMUM_NUMBER_LENGTH} to disable + * this check. + * @return An object which is the value. + */ + public BigInteger optBigInteger(String key, BigInteger defaultValue, + JSONParserConfiguration jsonParserConfiguration) { Object val = this.opt(key); - return objectToBigInteger(val, defaultValue); + return objectToBigInteger(val, defaultValue, jsonParserConfiguration); } /** @@ -1392,9 +1436,29 @@ public BigInteger optBigInteger(String key, BigInteger defaultValue) { * to convert. */ static BigInteger objectToBigInteger(Object val, BigInteger defaultValue) { + return objectToBigInteger(val, defaultValue, new JSONParserConfiguration()); + } + + /** + * @param val value to convert + * @param defaultValue default value to return is the conversion doesn't work or is null. + * @param jsonParserConfiguration parser configuration whose {@code maxNumberLength} + * bounds the number of decimal digits in the resulting integer. Values whose + * integer part would exceed this length are treated as unconvertible and + * {@code defaultValue} is returned. Pass a configuration with + * {@link ParserConfiguration#UNDEFINED_MAXIMUM_NUMBER_LENGTH} to disable this check. + * @return BigInteger conversion of the original value, or the defaultValue if unable + * to convert. + */ + static BigInteger objectToBigInteger(Object val, BigInteger defaultValue, + JSONParserConfiguration jsonParserConfiguration) { if (NULL.equals(val)) { return defaultValue; } + if (jsonParserConfiguration == null) { + jsonParserConfiguration = new JSONParserConfiguration(); + } + final int maxNumberLength = jsonParserConfiguration.getMaxNumberLength(); if (val instanceof BigInteger){ return (BigInteger) val; } @@ -1402,9 +1466,10 @@ static BigInteger objectToBigInteger(Object val, BigInteger defaultValue) { BigDecimal bd = (BigDecimal) val; // Same ceiling as the parse-time maxNumberLength guard: refuse to // materialise an integer whose decimal representation would exceed - // DEFAULT_MAX_NUMBER_LENGTH digits. Prevents DoS via short exponent - // literals like 1e100000000 (CVE-2026-59171, see issue #1063). - if ((long) bd.precision() - bd.scale() > ParserConfiguration.DEFAULT_MAX_NUMBER_LENGTH) { + // maxNumberLength digits. Prevents DoS via short exponent literals + // like 1e100000000 (CVE-2026-59171, see issue #1063). + if (maxNumberLength != ParserConfiguration.UNDEFINED_MAXIMUM_NUMBER_LENGTH + && (long) bd.precision() - bd.scale() > maxNumberLength) { return defaultValue; } return bd.toBigInteger(); @@ -1431,7 +1496,8 @@ static BigInteger objectToBigInteger(Object val, BigInteger defaultValue) { final String valStr = val.toString(); if(isDecimalNotation(valStr)) { BigDecimal bd = new BigDecimal(valStr); - if ((long) bd.precision() - bd.scale() > ParserConfiguration.DEFAULT_MAX_NUMBER_LENGTH) { + if (maxNumberLength != ParserConfiguration.UNDEFINED_MAXIMUM_NUMBER_LENGTH + && (long) bd.precision() - bd.scale() > maxNumberLength) { return defaultValue; } return bd.toBigInteger(); diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 5ac4643d8..fabaa5a31 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1405,6 +1405,58 @@ public void getBigIntegerHugeExponentReturnsDefault() { jo3.getBigInteger("x").compareTo(BigInteger.TEN.pow(999))); } + /** + * Verifies that the JSONParserConfiguration.maxNumberLength setting is honoured + * by the getBigInteger / optBigInteger overloads on JSONObject and JSONArray. + */ + @Test(timeout = 5000) + public void getBigIntegerHonorsMaxNumberLengthConfig() { + JSONObject jo = new JSONObject("{\"a\":1e1500,\"b\":1e2500}"); + + // Default config: DEFAULT_MAX_NUMBER_LENGTH == 1000, both rejected + assertNull("1e1500 rejected under default", jo.optBigInteger("a", null)); + assertNull("1e2500 rejected under default", jo.optBigInteger("b", null)); + + // Custom raised limit + JSONParserConfiguration cfg2000 = new JSONParserConfiguration().withMaxNumberLength(2000); + assertEquals("1e1500 accepted under maxNumberLength=2000", 0, + jo.getBigInteger("a", cfg2000).compareTo(BigInteger.TEN.pow(1500))); + assertNull("1e2500 rejected under maxNumberLength=2000", + jo.optBigInteger("b", null, cfg2000)); + try { + jo.getBigInteger("b", cfg2000); + fail("getBigInteger should throw for 1e2500 under maxNumberLength=2000"); + } catch (JSONException expected) { + // expected: integer part exceeds configured maxNumberLength + } + + // Custom lowered limit + JSONParserConfiguration cfg5 = new JSONParserConfiguration().withMaxNumberLength(5); + assertNull("1e1500 rejected under maxNumberLength=5", + jo.optBigInteger("a", null, cfg5)); + JSONObject small = new JSONObject("{\"x\":1234}"); + assertEquals("small value accepted under maxNumberLength=5", + BigInteger.valueOf(1234), small.getBigInteger("x", cfg5)); + + // Disabled: -1 turns the guard off. Use a moderate exponent so the test + // completes in a few ms while still exceeding the default limit. + JSONParserConfiguration cfgOff = new JSONParserConfiguration() + .withMaxNumberLength(ParserConfiguration.UNDEFINED_MAXIMUM_NUMBER_LENGTH); + assertEquals("1e2500 accepted when maxNumberLength is disabled", 0, + jo.getBigInteger("b", cfgOff).compareTo(BigInteger.TEN.pow(2500))); + + // null config falls back to default + assertNull("null config behaves like default", jo.optBigInteger("a", null, null)); + + // JSONArray overloads follow the same rules + JSONArray ja = new JSONArray("[1e1500]"); + assertNull("array: 1e1500 rejected under default", ja.optBigInteger(0, null)); + assertEquals("array: 1e1500 accepted under maxNumberLength=2000", 0, + ja.getBigInteger(0, cfg2000).compareTo(BigInteger.TEN.pow(1500))); + assertEquals("array: 1e1500 accepted when disabled", 0, + ja.optBigInteger(0, null, cfgOff).compareTo(BigInteger.TEN.pow(1500))); + } + /** * The purpose for the static method getNames() methods are not clear. This * method is not called from within JSON-Java. Most likely uses are to prep From 9953b760502800f7871cd942a6c920c4306edf60 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Thu, 16 Jul 2026 13:23:39 -0500 Subject: [PATCH 05/33] max-number-length-config sonarqube fixes --- src/main/java/org/json/JSONObject.java | 14 +++++++++++++- src/main/java/org/json/ParserConfiguration.java | 3 ++- src/main/java/org/json/XML.java | 2 +- 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/json/JSONObject.java b/src/main/java/org/json/JSONObject.java index bf9f92007..bcd218e5d 100644 --- a/src/main/java/org/json/JSONObject.java +++ b/src/main/java/org/json/JSONObject.java @@ -1484,6 +1484,18 @@ static BigInteger objectToBigInteger(Object val, BigInteger defaultValue, || val instanceof Short || val instanceof Byte){ return BigInteger.valueOf(((Number) val).longValue()); } + return attemptConversionToBigInteger(val, defaultValue, maxNumberLength); + } + + /** + * Convenience method to attempt conversion of value to BigInteger. + * Added to reduce complexity of objectToBigInteger() + * @param val the value to be converted + * @param defaultValue the default value to use if conversion is not attempted or fails + * @param maxNumberLength the max length allowed for BigIntegers + * @return the converted value, or the defaultValue + */ + private static BigInteger attemptConversionToBigInteger(Object val, BigInteger defaultValue, int maxNumberLength) { // don't check if it's a string in case of unchecked Number subclasses try { /** @@ -2799,7 +2811,7 @@ public static Object stringToValue(String string, JSONParserConfiguration jsonPa jsonParserConfiguration = new JSONParserConfiguration(); } // user declines max number checking - if (jsonParserConfiguration.getMaxNumberLength() == JSONParserConfiguration.UNDEFINED_MAXIMUM_NUMBER_LENGTH) { + if (jsonParserConfiguration.getMaxNumberLength() == ParserConfiguration.UNDEFINED_MAXIMUM_NUMBER_LENGTH) { return stringToNumber(string); } if (string.length() <= jsonParserConfiguration.getMaxNumberLength()) { diff --git a/src/main/java/org/json/ParserConfiguration.java b/src/main/java/org/json/ParserConfiguration.java index df700b355..e80093cac 100644 --- a/src/main/java/org/json/ParserConfiguration.java +++ b/src/main/java/org/json/ParserConfiguration.java @@ -58,8 +58,9 @@ public ParserConfiguration() { * * @param keepStrings A boolean indicating whether to preserve strings during parsing. * @param maxNestingDepth An integer representing the maximum allowed nesting depth. - * @deprecated + * @deprecated Use the with*() methods instead */ + @Deprecated protected ParserConfiguration(final boolean keepStrings, final int maxNestingDepth) { this.keepStrings = keepStrings; this.maxNestingDepth = maxNestingDepth; diff --git a/src/main/java/org/json/XML.java b/src/main/java/org/json/XML.java index 195da8d5d..32475876c 100644 --- a/src/main/java/org/json/XML.java +++ b/src/main/java/org/json/XML.java @@ -667,7 +667,7 @@ public static Object stringToValue(String string, XMLParserConfiguration xmlPars if ((initial >= '0' && initial <= '9') || initial == '-') { try { // user declines max number checking - if (xmlParserConfiguration.getMaxNumberLength() == JSONParserConfiguration.UNDEFINED_MAXIMUM_NUMBER_LENGTH) { + if (xmlParserConfiguration.getMaxNumberLength() == ParserConfiguration.UNDEFINED_MAXIMUM_NUMBER_LENGTH) { return stringToNumber(string); } if(string.length() <= xmlParserConfiguration.getMaxNumberLength()) { From d24bc9e5d6e9c79de0c154992108a91ce5c8970b Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sun, 19 Jul 2026 12:51:08 -0500 Subject: [PATCH 06/33] pre-release-20260719 initial commit --- README.md | 2 +- build.gradle | 2 +- docs/RELEASES.md | 2 ++ pom.xml | 2 +- 4 files changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 40acb8f06..b60cd1827 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ JSON in Java [package org.json] [![CodeQL](https://github.com/stleary/JSON-java/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/stleary/JSON-java/actions/workflows/codeql-analysis.yml) [![javadoc](https://javadoc.io/badge2/org.json/json/javadoc.svg)](https://javadoc.io/doc/org.json/json) -**[Click here if you just want the latest release jar file.](https://search.maven.org/remotecontent?filepath=org/json/json/20260522/json-20260522.jar)** +**[Click here if you just want the latest release jar file.](https://search.maven.org/remotecontent?filepath=org/json/json/202607119/json-20260719.jar)** # Overview diff --git a/build.gradle b/build.gradle index d8b69805f..f9251816c 100644 --- a/build.gradle +++ b/build.gradle @@ -42,7 +42,7 @@ subprojects { } group = 'org.json' -version = 'v20260522-SNAPSHOT' +version = 'v20260719-SNAPSHOT' description = 'JSON in Java' sourceCompatibility = '1.8' diff --git a/docs/RELEASES.md b/docs/RELEASES.md index 7513766ff..43edf3ae5 100644 --- a/docs/RELEASES.md +++ b/docs/RELEASES.md @@ -5,6 +5,8 @@ and artifactId "json". For example: [https://search.maven.org/search?q=g:org.json%20AND%20a:json&core=gav](https://search.maven.org/search?q=g:org.json%20AND%20a:json&core=gav) ~~~ +20260719 Fixes CVE-2026-59171 very large BigInteger, BigDecimal + 20260522 Publish key data, recent commits for minor fixes 20251224 Records, fromJson(), and recent commits diff --git a/pom.xml b/pom.xml index 3f15d6896..d5fb42ddc 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ org.json json - 20260522 + 20260719 bundle JSON in Java From da757c6656a84fe87cb4442f16153b3efe2ccaf3 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sun, 19 Jul 2026 13:48:18 -0500 Subject: [PATCH 07/33] pre-release-20260719 oops forgot to update new unit tests for strict mode --- .../java/org/json/junit/JSONObjectTest.java | 87 ++++++++++++------- 1 file changed, 57 insertions(+), 30 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index fabaa5a31..6b692789e 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -3885,6 +3885,7 @@ public void jsonObjectParseFromJson_9() { @Test public void testMaxNumberLength() { + JSONParserConfiguration jsonParserConfiguration = new JSONParserConfiguration(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 100; ++i) { sb.append("9999999999"); @@ -3896,11 +3897,14 @@ public void testMaxNumberLength() { // JSONArray with number just under the max length limit checkJSONArrayMaxLen(sb.toString(), true, null); - // JSONObject with number just over the max length limit - checkJSONObjectMaxLen(sb + "9", false, null); + // numbers without quotes are not allowed in strict mode + if (!jsonParserConfiguration.isStrictMode()) { + // JSONObject with number just over the max length limit + checkJSONObjectMaxLen(sb + "9", false, null); - // JSONArray with number just over the max length limit - checkJSONArrayMaxLen(sb + "9", false, null); + // JSONArray with number just over the max length limit + checkJSONArrayMaxLen(sb + "9", false, null); + } // JSONObject with number at config max length limit checkJSONObjectMaxLen(sb.toString() + sb.toString(), true, new JSONParserConfiguration().withMaxNumberLength(2000)); @@ -3908,11 +3912,14 @@ public void testMaxNumberLength() { // JSONArray with number at config max length limit checkJSONArrayMaxLen((sb.toString() + sb), true, new JSONParserConfiguration().withMaxNumberLength(2000)); - // JSONObject with number just over config max length limit - checkJSONObjectMaxLen(sb.toString() + sb.toString() + "9", false, new JSONParserConfiguration().withMaxNumberLength(2000)); + // numbers without quotes are not allowed in strict mode + if (!jsonParserConfiguration.isStrictMode()) { + // JSONObject with number just over config max length limit + checkJSONObjectMaxLen(sb.toString() + sb.toString() + "9", false, new JSONParserConfiguration().withMaxNumberLength(2000)); - // JSONArray with number just over config max length limit - checkJSONArrayMaxLen((sb.toString() + sb + "9"), false, new JSONParserConfiguration().withMaxNumberLength(2000)); + // JSONArray with number just over config max length limit + checkJSONArrayMaxLen((sb.toString() + sb + "9"), false, new JSONParserConfiguration().withMaxNumberLength(2000)); + } // JSONObject with large number, no checks checkJSONObjectMaxLen(sb.toString() + sb.toString() + "9", true, @@ -3975,6 +3982,8 @@ private static void checkJSONArrayMaxLen(String s, boolean isValid, JSONParserCo */ @Test public void testMaxNumberLengthNegativeInteger() { + JSONParserConfiguration jsonParserConfiguration = new JSONParserConfiguration(); + // Build a negative number string of exactly 1000 chars: "-" + 999 digits StringBuilder sb = new StringBuilder("-"); for (int i = 0; i < 999; ++i) { @@ -3985,10 +3994,13 @@ public void testMaxNumberLengthNegativeInteger() { // at max length: parsed as number checkJSONObjectMaxLen(sb.toString(), true, null); - // over max length: returned as string - sb.append("1"); - assertEquals(1001, sb.length()); - checkJSONObjectMaxLen(sb.toString(), false, null); + // numbers without quotes are not allowed in strict mode + if (!jsonParserConfiguration.isStrictMode()) { + // over max length: returned as string + sb.append("1"); + assertEquals(1001, sb.length()); + checkJSONObjectMaxLen(sb.toString(), false, null); + } } /** @@ -3996,6 +4008,8 @@ public void testMaxNumberLengthNegativeInteger() { */ @Test public void testMaxNumberLengthDecimal() { + JSONParserConfiguration jsonParserConfiguration = new JSONParserConfiguration(); + // Build a decimal number string of exactly 1000 chars: 499 digits + "." + 500 // digits StringBuilder sb = new StringBuilder(); @@ -4011,10 +4025,13 @@ public void testMaxNumberLengthDecimal() { // at max length: parsed as number (BigDecimal) checkJSONObjectMaxLen(sb.toString(), true, null); - // over max length: returned as string - sb.append("3"); - assertEquals(1001, sb.length()); - checkJSONObjectMaxLen(sb.toString(), false, null); + // numbers without quotes are not allowed in strict mode + if (!jsonParserConfiguration.isStrictMode()) { + // over max length: returned as string + sb.append("3"); + assertEquals(1001, sb.length()); + checkJSONObjectMaxLen(sb.toString(), false, null); + } } /** @@ -4022,6 +4039,8 @@ public void testMaxNumberLengthDecimal() { */ @Test public void testMaxNumberLengthScientificNotation() { + JSONParserConfiguration jsonParserConfiguration = new JSONParserConfiguration(); + // Build a scientific notation string of exactly 1000 chars StringBuilder sb = new StringBuilder("1."); for (int i = 0; i < 994; ++i) { @@ -4038,9 +4057,13 @@ public void testMaxNumberLengthScientificNotation() { for (int i = 0; i < 995; ++i) { sb.append("0"); } - sb.append("e100"); - assertEquals(1001, sb.length()); - checkJSONObjectMaxLen(sb.toString(), false, null); + + // numbers without quotes are not allowed in strict mode + if (!jsonParserConfiguration.isStrictMode()) { + sb.append("e100"); + assertEquals(1001, sb.length()); + checkJSONObjectMaxLen(sb.toString(), false, null); + } } /** @@ -4297,17 +4320,21 @@ public void testStringToValueViaJSONObject() { */ @Test public void testStringToNumberInvalidFormats() { - // Leading zero followed by digit → treated as string (not octal) - JSONObject jo = new JSONObject("{\"a\": 01}"); - // JSONTokener with strict mode would reject, but default mode stores as string - // since stringToNumber throws NumberFormatException for "01" - Object val = jo.get("a"); - assertTrue("01 should be stored as string, got " + val.getClass(), val instanceof String); - - // Negative with leading zero → "-01" - jo = new JSONObject("{\"a\": -01}"); - val = jo.get("a"); - assertTrue("-01 should be stored as string, got " + val.getClass(), val instanceof String); + // this test should only run in non-strict mode, otherwise it will throw an exception + JSONParserConfiguration jsonParserConfiguration = new JSONParserConfiguration(); + if (!jsonParserConfiguration.isStrictMode()) { + // Leading zero followed by digit → treated as string (not octal) + JSONObject jo = new JSONObject("{\"a\": 01}"); + // JSONTokener with strict mode would reject, but default mode stores as string + // since stringToNumber throws NumberFormatException for "01" + Object val = jo.get("a"); + assertTrue("01 should be stored as string, got " + val.getClass(), val instanceof String); + + // Negative with leading zero → "-01" + jo = new JSONObject("{\"a\": -01}"); + val = jo.get("a"); + assertTrue("-01 should be stored as string, got " + val.getClass(), val instanceof String); + } } } From 94854a1dfafdf7ecf168a60593240ecce13e7634 Mon Sep 17 00:00:00 2001 From: dong0713 <417851790@qq.com> Date: Mon, 20 Jul 2026 17:42:02 +0800 Subject: [PATCH 08/33] Fix XML.unescape rejecting valid whitespace numeric character references XML.mustEscape() is shared by both XML.escape() (serialization) and XMLTokener.unescapeEntity() (deserialization). While the method's Javadoc and comment quote the W3C XML 1.0 valid-character range (#x9 | #xA | #xD | [#x20-#xD7FF] | ...), the implementation only checked [#x20-#xD7FF] in its range clause, omitting #x9/#xA/#xD. Although the ISO-control clause excluded those three codepoints, the negated range clause still marked them as 'must escape', so unescapeEntity() threw JSONException for the XML-allowed control characters TAB, LF and CR. This broke XML.unescape(" ") and XML.toJSONObject(" "), both of which worked in v20251224 and regressed after #1045 (v20260522). Align the range clause with the W3C spec by explicitly allowing #x9, #xA and #xD, matching the comment that was already documented. Fixes #1059 --- src/main/java/org/json/XML.java | 10 ++++-- src/test/java/org/json/junit/XMLTest.java | 37 +++++++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/json/XML.java b/src/main/java/org/json/XML.java index 32475876c..f5846cc1e 100644 --- a/src/main/java/org/json/XML.java +++ b/src/main/java/org/json/XML.java @@ -172,8 +172,14 @@ static boolean mustEscape(int cp) { && cp != 0xA && cp != 0xD ) || !( - // valid the range of acceptable characters that aren't control - (cp >= 0x20 && cp <= 0xD7FF) + // Valid character range per W3C XML 1.0 spec: + // #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] + // Previously omitted #x9/#xA/#xD, causing unescape(" ") etc. + // to reject valid LF/TAB/CR as illegal (see #1059) + cp == 0x9 + || cp == 0xA + || cp == 0xD + || (cp >= 0x20 && cp <= 0xD7FF) || (cp >= 0xE000 && cp <= 0xFFFD) || (cp >= 0x10000 && cp <= 0x10FFFF) ) diff --git a/src/test/java/org/json/junit/XMLTest.java b/src/test/java/org/json/junit/XMLTest.java index 589536fd2..44fdcccb4 100644 --- a/src/test/java/org/json/junit/XMLTest.java +++ b/src/test/java/org/json/junit/XMLTest.java @@ -1537,6 +1537,43 @@ public void testValidUppercaseHexEntity() { assertEquals("A", jsonObject.getString("a")); } + /** + * Tests that valid XML numeric character references for whitespace + * control characters (TAB, LF, CR) are correctly unescaped. These + * codepoints are explicitly allowed by the XML 1.0 spec + * (https://www.w3.org/TR/REC-xml/#charsets) but were previously rejected + * as invalid. See issue #1059. + */ + @Test + public void testValidWhitespaceNumericEntityUnescape() { + // decimal references for the three allowed control characters + assertEquals("\t", XML.unescape(" ")); + assertEquals("\n", XML.unescape(" ")); + assertEquals("\r", XML.unescape(" ")); + // hex references for the same codepoints + assertEquals("\t", XML.unescape(" ")); + assertEquals("\n", XML.unescape(" ")); + assertEquals("\r", XML.unescape(" ")); + } + + /** + * Tests that {@code XML.toJSONObject} accepts numeric character references + * for the XML-allowed control characters (TAB, LF, CR) without throwing. + * Regression test for #1059, where {@code XML.toJSONObject(" ")} + * threw JSONException in versions after 20251224. + */ + @Test + public void testValidWhitespaceNumericEntityToJSONObject() { + // LF reference should round-trip through toJSONObject without throwing + JSONObject jsonObject = XML.toJSONObject(" "); + // the value is the LF character (possibly trimmed by the JSON path, + // but the call must not throw) + assertTrue(jsonObject.has("a")); + // TAB and CR references also accepted + XML.toJSONObject(" "); + XML.toJSONObject(" "); + } + } From e2cfb5a64150455bf63ad334da9827e7671c9133 Mon Sep 17 00:00:00 2001 From: Mirko Swillus Date: Thu, 23 Jul 2026 14:36:42 +0200 Subject: [PATCH 09/33] #1071: reject invalid XML element names in XML.toString (CWE-91) XML.toString emitted JSONObject keys verbatim as tag names, so a key containing '<', '>' or '/' broke out of its element and injected arbitrary sibling structure into the output. Per #294/#123 the agreed approach is to throw on invalid input rather than mangle it. - Add mustBeXmlName / isXmlNameStart / isXmlNameChar implementing the XML 1.0 (5th ed.) Name production, code-point aware. - Validate tagName at method entry and each key at the top of the key loop (skipping the cDataTagName sentinel). - Rewrite XMLTest.shouldHandleIllegalJSONNodeNames and XMLConfigurationTest.shouldHandleIllegalJSONNodeNames (previously documenting the pass-through behaviour) to assert the throw. - Add XMLTest.toStringRejectsElementInjectionInKey covering the #1071 payload and an invalid caller-supplied tagName. - Add XMLTest.toStringAcceptsValidXmlNames covering hyphen/dot/ underscore/colon, Latin-1 letters, and the cDataTagName sentinel. Fixes #1071. Also resolves the long-standing well-formedness question in #166 / #294 / #308. Co-Authored-By: Claude --- src/main/java/org/json/XML.java | 76 ++++++++++++++++++ .../org/json/junit/XMLConfigurationTest.java | 43 +++++----- src/test/java/org/json/junit/XMLTest.java | 80 ++++++++++++++----- 3 files changed, 159 insertions(+), 40 deletions(-) diff --git a/src/main/java/org/json/XML.java b/src/main/java/org/json/XML.java index 32475876c..c924a8179 100644 --- a/src/main/java/org/json/XML.java +++ b/src/main/java/org/json/XML.java @@ -232,6 +232,75 @@ public static void noSpace(String string) throws JSONException { } } + /** + * Throw an exception if the string is not a valid XML 1.0 {@code Name} + * (element name). Used by {@link #toString(Object)} to reject JSON keys that + * would otherwise be emitted verbatim between {@code <} and {@code >} and + * could break out of the tag context (element injection, CWE-91; + * see issue #1071 and #294). + * + * @param string the candidate element name + * @throws JSONException if {@code string} is null, empty, or contains a + * character outside the XML 1.0 Name production + */ + static void mustBeXmlName(String string) throws JSONException { + if (string == null || string.isEmpty()) { + throw new JSONException("'" + string + + "' is not a valid XML element name."); + } + int cp = string.codePointAt(0); + if (!isXmlNameStart(cp)) { + throw new JSONException("'" + string + + "' is not a valid XML element name."); + } + for (int i = Character.charCount(cp); i < string.length(); i += Character.charCount(cp)) { + cp = string.codePointAt(i); + if (!isXmlNameChar(cp)) { + throw new JSONException("'" + string + + "' is not a valid XML element name."); + } + } + } + + /** + * XML 1.0 (5th ed.) {@code NameStartChar} production. + * + * @param cp a Unicode code point + * @return true if {@code cp} may start an XML Name + */ + private static boolean isXmlNameStart(int cp) { + return cp == ':' || cp == '_' + || (cp >= 'A' && cp <= 'Z') + || (cp >= 'a' && cp <= 'z') + || (cp >= 0xC0 && cp <= 0xD6) + || (cp >= 0xD8 && cp <= 0xF6) + || (cp >= 0xF8 && cp <= 0x2FF) + || (cp >= 0x370 && cp <= 0x37D) + || (cp >= 0x37F && cp <= 0x1FFF) + || (cp >= 0x200C && cp <= 0x200D) + || (cp >= 0x2070 && cp <= 0x218F) + || (cp >= 0x2C00 && cp <= 0x2FEF) + || (cp >= 0x3001 && cp <= 0xD7FF) + || (cp >= 0xF900 && cp <= 0xFDCF) + || (cp >= 0xFDF0 && cp <= 0xFFFD) + || (cp >= 0x10000 && cp <= 0xEFFFF); + } + + /** + * XML 1.0 (5th ed.) {@code NameChar} production. + * + * @param cp a Unicode code point + * @return true if {@code cp} may appear after the first character of an XML Name + */ + private static boolean isXmlNameChar(int cp) { + return isXmlNameStart(cp) + || cp == '-' || cp == '.' + || (cp >= '0' && cp <= '9') + || cp == 0xB7 + || (cp >= 0x0300 && cp <= 0x036F) + || (cp >= 0x203F && cp <= 0x2040); + } + /** * Scan the content following the named tag, attaching it to the context. * @@ -968,6 +1037,10 @@ private static String toString(final Object object, final String tagName, final JSONObject jo; String string; + if (tagName != null) { + mustBeXmlName(tagName); + } + if (object instanceof JSONObject) { // Emit @@ -986,6 +1059,9 @@ private static String toString(final Object object, final String tagName, final // don't use the new entrySet accessor to maintain Android Support jo = (JSONObject) object; for (final String key : jo.keySet()) { + if (!key.equals(config.getcDataTagName())) { + mustBeXmlName(key); + } Object value = jo.opt(key); if (value == null) { value = ""; diff --git a/src/test/java/org/json/junit/XMLConfigurationTest.java b/src/test/java/org/json/junit/XMLConfigurationTest.java index e8ff3b60c..1a1a2fd58 100755 --- a/src/test/java/org/json/junit/XMLConfigurationTest.java +++ b/src/test/java/org/json/junit/XMLConfigurationTest.java @@ -506,32 +506,31 @@ public void shouldHandleNestedArraytoString() { /** - * Possible bug: - * Illegal node-names must be converted to legal XML-node-names. - * The given example shows 2 nodes which are valid for JSON, but not for XML. - * Therefore illegal arguments should be converted to e.g. an underscore (_). + * JSON keys that are not valid XML 1.0 Names are rejected by + * XML.toString rather than being emitted as (malformed) tag names. + * See issues #166, #294, #308 and #1071. */ @Test public void shouldHandleIllegalJSONNodeNames() { - JSONObject inputJSON = new JSONObject(); - inputJSON.append("123IllegalNode", "someValue1"); - inputJSON.append("Illegal@node", "someValue2"); - - String result = XML.toString(inputJSON, null, - XMLParserConfiguration.KEEP_STRINGS); - - /* - * This is invalid XML. Names should not begin with digits or contain - * certain values, including '@'. One possible solution is to replace - * illegal chars with '_', in which case the expected output would be: - * <___IllegalNode>someValue1someValue2 - */ - String expected = "<123IllegalNode>someValue1someValue2"; - - assertEquals("Length", expected.length(), result.length()); - assertTrue("123IllegalNode", result.contains("<123IllegalNode>someValue1")); - assertTrue("Illegal@node", result.contains("someValue2")); + // Name may not start with a digit + try { + XML.toString(new JSONObject().append("123IllegalNode", "someValue1"), + null, XMLParserConfiguration.KEEP_STRINGS); + fail("expected JSONException for digit-leading element name"); + } catch (JSONException expected) { + assertTrue("message names the offending key", + expected.getMessage().contains("123IllegalNode")); + } + // Name may not contain '@' + try { + XML.toString(new JSONObject().append("Illegal@node", "someValue2"), + null, XMLParserConfiguration.KEEP_STRINGS); + fail("expected JSONException for '@' in element name"); + } catch (JSONException expected) { + assertTrue("message names the offending key", + expected.getMessage().contains("Illegal@node")); + } } /** diff --git a/src/test/java/org/json/junit/XMLTest.java b/src/test/java/org/json/junit/XMLTest.java index 589536fd2..e67b9de59 100644 --- a/src/test/java/org/json/junit/XMLTest.java +++ b/src/test/java/org/json/junit/XMLTest.java @@ -538,31 +538,75 @@ public void shouldHandleNestedArraytoString() { /** - * Possible bug: - * Illegal node-names must be converted to legal XML-node-names. - * The given example shows 2 nodes which are valid for JSON, but not for XML. - * Therefore illegal arguments should be converted to e.g. an underscore (_). + * JSON keys that are not valid XML 1.0 Names are rejected by + * XML.toString rather than being emitted as (malformed) tag names. + * See issues #166, #294, #308 and #1071. */ @Test public void shouldHandleIllegalJSONNodeNames() { - JSONObject inputJSON = new JSONObject(); - inputJSON.append("123IllegalNode", "someValue1"); - inputJSON.append("Illegal@node", "someValue2"); + // Name may not start with a digit + try { + XML.toString(new JSONObject().append("123IllegalNode", "someValue1")); + fail("expected JSONException for digit-leading element name"); + } catch (JSONException expected) { + assertTrue("message names the offending key", + expected.getMessage().contains("123IllegalNode")); + } + // Name may not contain '@' + try { + XML.toString(new JSONObject().append("Illegal@node", "someValue2")); + fail("expected JSONException for '@' in element name"); + } catch (JSONException expected) { + assertTrue("message names the offending key", + expected.getMessage().contains("Illegal@node")); + } + } - String result = XML.toString(inputJSON); + /** + * A JSON key containing XML metacharacters must not be emitted as a raw + * tag name, since doing so allows the key to break out of its element and + * inject sibling structure into the output (CWE-91, issue #1071). + */ + @Test + public void toStringRejectsElementInjectionInKey() + { + JSONObject jo = new JSONObject( + "{\"a/>evil' are outside the XML Name production + } - /* - * This is invalid XML. Names should not begin with digits or contain - * certain values, including '@'. One possible solution is to replace - * illegal chars with '_', in which case the expected output would be: - * <___IllegalNode>someValue1someValue2 - */ - String expected = "<123IllegalNode>someValue1someValue2"; + // caller-supplied tagName is validated too + try { + XML.toString(new JSONObject(), "bad tag"); + fail("expected JSONException for tagName containing whitespace"); + } catch (JSONException expected) { + // expected: space is outside the XML Name production + } + } - assertEquals("length",expected.length(), result.length()); - assertTrue("123IllegalNode",result.contains("<123IllegalNode>someValue1")); - assertTrue("Illegal@node",result.contains("someValue2")); + /** + * Keys that are valid XML 1.0 Names continue to serialise unchanged. + */ + @Test + public void toStringAcceptsValidXmlNames() + { + JSONObject jo = new JSONObject(); + jo.put("simple", "a"); + jo.put("with-hyphen.dot_underscore", "b"); + jo.put("ns:qualified", "c"); + jo.put("élément", "d"); // Latin-1 letters + jo.put("content", "e"); // cDataTagName sentinel, emitted as text + String xml = XML.toString(jo, "root"); + assertTrue(xml.contains("a")); + assertTrue(xml.contains("b")); + assertTrue(xml.contains("c")); + assertTrue(xml.contains("<élément>d")); + assertTrue("cDataTagName still emitted as text content", xml.contains(">e<")); } /** From 6b993e2e47b9a328a9d166a720b33fa7e3e58848 Mon Sep 17 00:00:00 2001 From: Mirko Swillus Date: Fri, 24 Jul 2026 10:57:24 +0200 Subject: [PATCH 10/33] #1071: extract inRange helper to satisfy Sonar S3776 isXmlNameStart's alternating &&/|| chain scored cognitive complexity 28. Extracting inRange(cp, lo, hi) collapses it to a flat || sequence and keeps the range list 1:1 with the XML 1.0 NameStartChar production. isXmlNameChar updated the same way. No behaviour change. Co-Authored-By: Claude --- src/main/java/org/json/XML.java | 44 +++++++++++++++++++-------------- 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/src/main/java/org/json/XML.java b/src/main/java/org/json/XML.java index c924a8179..5191cdf97 100644 --- a/src/main/java/org/json/XML.java +++ b/src/main/java/org/json/XML.java @@ -262,6 +262,10 @@ static void mustBeXmlName(String string) throws JSONException { } } + private static boolean inRange(int cp, int lo, int hi) { + return cp >= lo && cp <= hi; + } + /** * XML 1.0 (5th ed.) {@code NameStartChar} production. * @@ -269,21 +273,22 @@ static void mustBeXmlName(String string) throws JSONException { * @return true if {@code cp} may start an XML Name */ private static boolean isXmlNameStart(int cp) { - return cp == ':' || cp == '_' - || (cp >= 'A' && cp <= 'Z') - || (cp >= 'a' && cp <= 'z') - || (cp >= 0xC0 && cp <= 0xD6) - || (cp >= 0xD8 && cp <= 0xF6) - || (cp >= 0xF8 && cp <= 0x2FF) - || (cp >= 0x370 && cp <= 0x37D) - || (cp >= 0x37F && cp <= 0x1FFF) - || (cp >= 0x200C && cp <= 0x200D) - || (cp >= 0x2070 && cp <= 0x218F) - || (cp >= 0x2C00 && cp <= 0x2FEF) - || (cp >= 0x3001 && cp <= 0xD7FF) - || (cp >= 0xF900 && cp <= 0xFDCF) - || (cp >= 0xFDF0 && cp <= 0xFFFD) - || (cp >= 0x10000 && cp <= 0xEFFFF); + return cp == ':' + || cp == '_' + || inRange(cp, 'A', 'Z') + || inRange(cp, 'a', 'z') + || inRange(cp, 0xC0, 0xD6) + || inRange(cp, 0xD8, 0xF6) + || inRange(cp, 0xF8, 0x2FF) + || inRange(cp, 0x370, 0x37D) + || inRange(cp, 0x37F, 0x1FFF) + || inRange(cp, 0x200C, 0x200D) + || inRange(cp, 0x2070, 0x218F) + || inRange(cp, 0x2C00, 0x2FEF) + || inRange(cp, 0x3001, 0xD7FF) + || inRange(cp, 0xF900, 0xFDCF) + || inRange(cp, 0xFDF0, 0xFFFD) + || inRange(cp, 0x10000, 0xEFFFF); } /** @@ -294,11 +299,12 @@ private static boolean isXmlNameStart(int cp) { */ private static boolean isXmlNameChar(int cp) { return isXmlNameStart(cp) - || cp == '-' || cp == '.' - || (cp >= '0' && cp <= '9') + || cp == '-' + || cp == '.' || cp == 0xB7 - || (cp >= 0x0300 && cp <= 0x036F) - || (cp >= 0x203F && cp <= 0x2040); + || inRange(cp, '0', '9') + || inRange(cp, 0x0300, 0x036F) + || inRange(cp, 0x203F, 0x2040); } /** From 392a352901f509ad8c67fa6af3bea907f149dbeb Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Fri, 31 Jul 2026 15:26:28 -0500 Subject: [PATCH 11/33] Fix formatting of the latest release jar file link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b60cd1827..8adaa16d0 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ JSON in Java [package org.json] [![CodeQL](https://github.com/stleary/JSON-java/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/stleary/JSON-java/actions/workflows/codeql-analysis.yml) [![javadoc](https://javadoc.io/badge2/org.json/json/javadoc.svg)](https://javadoc.io/doc/org.json/json) -**[Click here if you just want the latest release jar file.](https://search.maven.org/remotecontent?filepath=org/json/json/202607119/json-20260719.jar)** +**[Click here if you just want the latest release jar file.](https://search.maven.org/remotecontent?filepath=org/json/json/20260719/json-20260719.jar)** # Overview From 22ab2fb7245bb0c1a766c6aa11c905aa82315ef3 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Fri, 31 Jul 2026 15:28:31 -0500 Subject: [PATCH 12/33] Update jar file link in README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8adaa16d0..75a5d37a1 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ JSON in Java [package org.json] [![CodeQL](https://github.com/stleary/JSON-java/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/stleary/JSON-java/actions/workflows/codeql-analysis.yml) [![javadoc](https://javadoc.io/badge2/org.json/json/javadoc.svg)](https://javadoc.io/doc/org.json/json) -**[Click here if you just want the latest release jar file.](https://search.maven.org/remotecontent?filepath=org/json/json/20260719/json-20260719.jar)** +**[Click here if you just want the latest release jar file.](https://repo1.maven.org/maven2/org/json/json/20260719/json-20260719.jar)** # Overview From 34efda6423492a1f7f38c52241ade88c308e6cc0 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Fri, 14 Aug 2026 10:54:22 -0500 Subject: [PATCH 13/33] pre-release-20260814 initial commit --- README.md | 2 +- build.gradle | 10 +++++++++- docs/RELEASES.md | 2 ++ pom.xml | 28 ++-------------------------- 4 files changed, 14 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 75a5d37a1..2536343ec 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ JSON in Java [package org.json] [![CodeQL](https://github.com/stleary/JSON-java/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/stleary/JSON-java/actions/workflows/codeql-analysis.yml) [![javadoc](https://javadoc.io/badge2/org.json/json/javadoc.svg)](https://javadoc.io/doc/org.json/json) -**[Click here if you just want the latest release jar file.](https://repo1.maven.org/maven2/org/json/json/20260719/json-20260719.jar)** +**[Click here if you just want the latest release jar file.](https://repo1.maven.org/maven2/org/json/json/20260814/json-20260814.jar)** # Overview diff --git a/build.gradle b/build.gradle index f9251816c..74ecd49a4 100644 --- a/build.gradle +++ b/build.gradle @@ -21,6 +21,7 @@ repositories { } // To view the report open build/reports/jacoco/test/html/index.html +// Note: disable jacocoTestReport and test blocks, and the jacoco plugin if it interferes with stepping in the debugger jacocoTestReport { reports { html.required = true @@ -31,6 +32,13 @@ test { finalizedBy jacocoTestReport } +// enable logging to stdout during test +tasks.withType(Test) { + testLogging { + showStandardStreams = true + } +} + dependencies { testImplementation 'junit:junit:4.13.2' testImplementation 'com.jayway.jsonpath:json-path:2.9.0' @@ -42,7 +50,7 @@ subprojects { } group = 'org.json' -version = 'v20260719-SNAPSHOT' +version = 'v20260814-SNAPSHOT' description = 'JSON in Java' sourceCompatibility = '1.8' diff --git a/docs/RELEASES.md b/docs/RELEASES.md index 43edf3ae5..e233a5749 100644 --- a/docs/RELEASES.md +++ b/docs/RELEASES.md @@ -5,6 +5,8 @@ and artifactId "json". For example: [https://search.maven.org/search?q=g:org.json%20AND%20a:json&core=gav](https://search.maven.org/search?q=g:org.json%20AND%20a:json&core=gav) ~~~ +20260814 Fixes XML.unescape whitespace handling + 20260719 Fixes CVE-2026-59171 very large BigInteger, BigDecimal 20260522 Publish key data, recent commits for minor fixes diff --git a/pom.xml b/pom.xml index d5fb42ddc..127f9c017 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ org.json json - 20260719 + 20260814 bundle JSON in Java @@ -46,20 +46,6 @@ UTF-8 - - - - ossrh - Central Repository OSSRH - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - - junit @@ -158,17 +144,7 @@ - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.3 - true - - ossrh - https://oss.sonatype.org/ - false - - + org.moditect moditect-maven-plugin From 3dd0ec02f25c7c8f716fd62e1e3ffc6254004275 Mon Sep 17 00:00:00 2001 From: Mirko Swillus Date: Thu, 20 Aug 2026 17:14:07 +0200 Subject: [PATCH 14/33] #1071: narrow tag-name check to XML metachars only Per review on #1072: reject only < > & " ' / in element names to close the CWE-91 injection vector, and drop the full XML 1.0 Name validation to preserve backwards compatibility for callers that emit non-well-formed but non-injecting tag names. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01MTGnYg5v1QxaqqfDKHKTVr --- src/main/java/org/json/XML.java | 83 ++++--------------- .../org/json/junit/XMLConfigurationTest.java | 43 +++++----- src/test/java/org/json/junit/XMLTest.java | 78 ++++++++--------- 3 files changed, 72 insertions(+), 132 deletions(-) diff --git a/src/main/java/org/json/XML.java b/src/main/java/org/json/XML.java index 5191cdf97..0dceb81a4 100644 --- a/src/main/java/org/json/XML.java +++ b/src/main/java/org/json/XML.java @@ -233,80 +233,27 @@ public static void noSpace(String string) throws JSONException { } /** - * Throw an exception if the string is not a valid XML 1.0 {@code Name} - * (element name). Used by {@link #toString(Object)} to reject JSON keys that - * would otherwise be emitted verbatim between {@code <} and {@code >} and - * could break out of the tag context (element injection, CWE-91; - * see issue #1071 and #294). + * Throw an exception if the string contains an XML metacharacter + * ({@code < > & " ' /}). Used by {@link #toString(Object)} to reject JSON + * keys that would otherwise be emitted verbatim between {@code <} and + * {@code >} and could break out of the tag context (element injection, + * CWE-91; see issue #1071). * * @param string the candidate element name - * @throws JSONException if {@code string} is null, empty, or contains a - * character outside the XML 1.0 Name production + * @throws JSONException if {@code string} contains an XML metacharacter */ - static void mustBeXmlName(String string) throws JSONException { - if (string == null || string.isEmpty()) { - throw new JSONException("'" + string - + "' is not a valid XML element name."); - } - int cp = string.codePointAt(0); - if (!isXmlNameStart(cp)) { - throw new JSONException("'" + string - + "' is not a valid XML element name."); - } - for (int i = Character.charCount(cp); i < string.length(); i += Character.charCount(cp)) { - cp = string.codePointAt(i); - if (!isXmlNameChar(cp)) { + static void noXmlMetachars(String string) throws JSONException { + int length = string.length(); + for (int i = 0; i < length; i++) { + char c = string.charAt(i); + if (c == '<' || c == '>' || c == '&' + || c == '"' || c == '\'' || c == '/') { throw new JSONException("'" + string - + "' is not a valid XML element name."); + + "' contains an XML metacharacter and may not be used as an element name."); } } } - private static boolean inRange(int cp, int lo, int hi) { - return cp >= lo && cp <= hi; - } - - /** - * XML 1.0 (5th ed.) {@code NameStartChar} production. - * - * @param cp a Unicode code point - * @return true if {@code cp} may start an XML Name - */ - private static boolean isXmlNameStart(int cp) { - return cp == ':' - || cp == '_' - || inRange(cp, 'A', 'Z') - || inRange(cp, 'a', 'z') - || inRange(cp, 0xC0, 0xD6) - || inRange(cp, 0xD8, 0xF6) - || inRange(cp, 0xF8, 0x2FF) - || inRange(cp, 0x370, 0x37D) - || inRange(cp, 0x37F, 0x1FFF) - || inRange(cp, 0x200C, 0x200D) - || inRange(cp, 0x2070, 0x218F) - || inRange(cp, 0x2C00, 0x2FEF) - || inRange(cp, 0x3001, 0xD7FF) - || inRange(cp, 0xF900, 0xFDCF) - || inRange(cp, 0xFDF0, 0xFFFD) - || inRange(cp, 0x10000, 0xEFFFF); - } - - /** - * XML 1.0 (5th ed.) {@code NameChar} production. - * - * @param cp a Unicode code point - * @return true if {@code cp} may appear after the first character of an XML Name - */ - private static boolean isXmlNameChar(int cp) { - return isXmlNameStart(cp) - || cp == '-' - || cp == '.' - || cp == 0xB7 - || inRange(cp, '0', '9') - || inRange(cp, 0x0300, 0x036F) - || inRange(cp, 0x203F, 0x2040); - } - /** * Scan the content following the named tag, attaching it to the context. * @@ -1044,7 +991,7 @@ private static String toString(final Object object, final String tagName, final String string; if (tagName != null) { - mustBeXmlName(tagName); + noXmlMetachars(tagName); } if (object instanceof JSONObject) { @@ -1066,7 +1013,7 @@ private static String toString(final Object object, final String tagName, final jo = (JSONObject) object; for (final String key : jo.keySet()) { if (!key.equals(config.getcDataTagName())) { - mustBeXmlName(key); + noXmlMetachars(key); } Object value = jo.opt(key); if (value == null) { diff --git a/src/test/java/org/json/junit/XMLConfigurationTest.java b/src/test/java/org/json/junit/XMLConfigurationTest.java index 1a1a2fd58..e8ff3b60c 100755 --- a/src/test/java/org/json/junit/XMLConfigurationTest.java +++ b/src/test/java/org/json/junit/XMLConfigurationTest.java @@ -506,31 +506,32 @@ public void shouldHandleNestedArraytoString() { /** - * JSON keys that are not valid XML 1.0 Names are rejected by - * XML.toString rather than being emitted as (malformed) tag names. - * See issues #166, #294, #308 and #1071. + * Possible bug: + * Illegal node-names must be converted to legal XML-node-names. + * The given example shows 2 nodes which are valid for JSON, but not for XML. + * Therefore illegal arguments should be converted to e.g. an underscore (_). */ @Test public void shouldHandleIllegalJSONNodeNames() { - // Name may not start with a digit - try { - XML.toString(new JSONObject().append("123IllegalNode", "someValue1"), - null, XMLParserConfiguration.KEEP_STRINGS); - fail("expected JSONException for digit-leading element name"); - } catch (JSONException expected) { - assertTrue("message names the offending key", - expected.getMessage().contains("123IllegalNode")); - } - // Name may not contain '@' - try { - XML.toString(new JSONObject().append("Illegal@node", "someValue2"), - null, XMLParserConfiguration.KEEP_STRINGS); - fail("expected JSONException for '@' in element name"); - } catch (JSONException expected) { - assertTrue("message names the offending key", - expected.getMessage().contains("Illegal@node")); - } + JSONObject inputJSON = new JSONObject(); + inputJSON.append("123IllegalNode", "someValue1"); + inputJSON.append("Illegal@node", "someValue2"); + + String result = XML.toString(inputJSON, null, + XMLParserConfiguration.KEEP_STRINGS); + + /* + * This is invalid XML. Names should not begin with digits or contain + * certain values, including '@'. One possible solution is to replace + * illegal chars with '_', in which case the expected output would be: + * <___IllegalNode>someValue1someValue2 + */ + String expected = "<123IllegalNode>someValue1someValue2"; + + assertEquals("Length", expected.length(), result.length()); + assertTrue("123IllegalNode", result.contains("<123IllegalNode>someValue1")); + assertTrue("Illegal@node", result.contains("someValue2")); } /** diff --git a/src/test/java/org/json/junit/XMLTest.java b/src/test/java/org/json/junit/XMLTest.java index e67b9de59..cd67c268e 100644 --- a/src/test/java/org/json/junit/XMLTest.java +++ b/src/test/java/org/json/junit/XMLTest.java @@ -538,29 +538,31 @@ public void shouldHandleNestedArraytoString() { /** - * JSON keys that are not valid XML 1.0 Names are rejected by - * XML.toString rather than being emitted as (malformed) tag names. - * See issues #166, #294, #308 and #1071. + * Possible bug: + * Illegal node-names must be converted to legal XML-node-names. + * The given example shows 2 nodes which are valid for JSON, but not for XML. + * Therefore illegal arguments should be converted to e.g. an underscore (_). */ @Test public void shouldHandleIllegalJSONNodeNames() { - // Name may not start with a digit - try { - XML.toString(new JSONObject().append("123IllegalNode", "someValue1")); - fail("expected JSONException for digit-leading element name"); - } catch (JSONException expected) { - assertTrue("message names the offending key", - expected.getMessage().contains("123IllegalNode")); - } - // Name may not contain '@' - try { - XML.toString(new JSONObject().append("Illegal@node", "someValue2")); - fail("expected JSONException for '@' in element name"); - } catch (JSONException expected) { - assertTrue("message names the offending key", - expected.getMessage().contains("Illegal@node")); - } + JSONObject inputJSON = new JSONObject(); + inputJSON.append("123IllegalNode", "someValue1"); + inputJSON.append("Illegal@node", "someValue2"); + + String result = XML.toString(inputJSON); + + /* + * This is invalid XML. Names should not begin with digits or contain + * certain values, including '@'. One possible solution is to replace + * illegal chars with '_', in which case the expected output would be: + * <___IllegalNode>someValue1someValue2 + */ + String expected = "<123IllegalNode>someValue1someValue2"; + + assertEquals("length",expected.length(), result.length()); + assertTrue("123IllegalNode",result.contains("<123IllegalNode>someValue1")); + assertTrue("Illegal@node",result.contains("someValue2")); } /** @@ -577,36 +579,26 @@ public void toStringRejectsElementInjectionInKey() XML.toString(jo, "root"); fail("expected JSONException for key containing XML metacharacters"); } catch (JSONException expected) { - // expected: '/', '<', '>' are outside the XML Name production + // expected: '/', '<', '>' are rejected in element names } - // caller-supplied tagName is validated too + // caller-supplied tagName is checked too try { - XML.toString(new JSONObject(), "bad tag"); - fail("expected JSONException for tagName containing whitespace"); + XML.toString(new JSONObject(), "bada")); - assertTrue(xml.contains("b")); - assertTrue(xml.contains("c")); - assertTrue(xml.contains("<élément>d")); - assertTrue("cDataTagName still emitted as text content", xml.contains(">e<")); + // each metacharacter is rejected individually + for (char c : new char[] {'<', '>', '&', '"', '\'', '/'}) { + try { + XML.toString(new JSONObject().put("a" + c + "b", "v")); + fail("expected JSONException for key containing '" + c + "'"); + } catch (JSONException expected) { + // expected + } + } } /** From bcbbc89568439d0b211482c6fd9d6fa12140d096 Mon Sep 17 00:00:00 2001 From: XIAYM-gh Date: Wed, 2 Sep 2026 20:31:40 +0800 Subject: [PATCH 15/33] Fixes corner case where strict mode isn't working when JSONTokener's next() and back() are called first --- src/main/java/org/json/JSONArray.java | 18 +++++++++++++--- src/main/java/org/json/JSONObject.java | 21 +++++++++++++++++-- src/main/java/org/json/JSONTokener.java | 13 ++++++++++-- .../java/org/json/junit/JSONArrayTest.java | 18 ++++++++++++++++ .../java/org/json/junit/JSONObjectTest.java | 18 ++++++++++++++++ 5 files changed, 81 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/json/JSONArray.java b/src/main/java/org/json/JSONArray.java index 0d7fde9df..62eca71fe 100644 --- a/src/main/java/org/json/JSONArray.java +++ b/src/main/java/org/json/JSONArray.java @@ -94,9 +94,21 @@ public JSONArray(JSONTokener x) throws JSONException { * @throws JSONException If a syntax error occurs during the construction of the JSONArray. */ public JSONArray(JSONTokener x, JSONParserConfiguration jsonParserConfiguration) throws JSONException { + this(x, jsonParserConfiguration, x.isAtStart()); + } + + /** + * Constructs a JSONArray from a JSONTokener and a JSONParserConfiguration, for internal use.
+ * Never call this instead of using withStrictMode(boolean). + * + * @param x A JSONTokener instance from which the JSONArray is constructed. + * @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser. + * @param eofRequired A boolean that determines whether this array is the root. + * @throws JSONException If a syntax error occurs during the construction of the JSONArray. + */ + JSONArray(JSONTokener x, JSONParserConfiguration jsonParserConfiguration, boolean eofRequired) throws JSONException { this(); - boolean isInitial = x.getPrevious() == 0; if (x.nextClean() != '[') { throw x.syntaxError("A JSONArray text must start with '['"); } @@ -118,10 +130,10 @@ public JSONArray(JSONTokener x, JSONParserConfiguration jsonParserConfiguration) x.back(); this.myArrayList.add(x.nextValue()); } - if (checkForSyntaxError(x, jsonParserConfiguration, isInitial)) return; + if (checkForSyntaxError(x, jsonParserConfiguration, eofRequired)) return; } } else { - if (isInitial && jsonParserConfiguration.isStrictMode() && x.nextClean() != 0) { + if (eofRequired && jsonParserConfiguration.isStrictMode() && x.nextClean() != 0) { throw x.syntaxError("Strict mode error: Unparsed characters found at end of input text"); } } diff --git a/src/main/java/org/json/JSONObject.java b/src/main/java/org/json/JSONObject.java index bcd218e5d..fcce72ab7 100644 --- a/src/main/java/org/json/JSONObject.java +++ b/src/main/java/org/json/JSONObject.java @@ -214,14 +214,31 @@ public JSONObject(JSONTokener x) throws JSONException { * duplicated key. */ public JSONObject(JSONTokener x, JSONParserConfiguration jsonParserConfiguration) throws JSONException { + this(x, jsonParserConfiguration, x.isAtStart()); + } + + /** + * Construct a JSONObject from a JSONTokener with custom json parse configurations, for internal use.
+ * Never call this instead of using withStrictMode(boolean). + * + * @param x + * A JSONTokener object containing the source string. + * @param jsonParserConfiguration + * Variable to pass parser custom configuration for json parsing. + * @param eofRequired + * A boolean that determines whether this object is the root. + * @throws JSONException + * If there is a syntax error in the source string or a + * duplicated key. + */ + JSONObject(JSONTokener x, JSONParserConfiguration jsonParserConfiguration, boolean eofRequired) throws JSONException { this(); - boolean isInitial = x.getPrevious() == 0; if (x.nextClean() != '{') { throw x.syntaxError("A JSONObject text must begin with '{'"); } for (;;) { - if (parseJSONObject(x, jsonParserConfiguration, isInitial)) { + if (parseJSONObject(x, jsonParserConfiguration, eofRequired)) { return; } } diff --git a/src/main/java/org/json/JSONTokener.java b/src/main/java/org/json/JSONTokener.java index 3726856d3..e8ae9fcf1 100644 --- a/src/main/java/org/json/JSONTokener.java +++ b/src/main/java/org/json/JSONTokener.java @@ -120,6 +120,15 @@ public void setJsonParserConfiguration(JSONParserConfiguration jsonParserConfigu this.jsonParserConfiguration = jsonParserConfiguration; } + /** + * Returns whether the tokener is currently positioned at the beginning, + * + * @return true if the current input position is the beginning + */ + public boolean isAtStart() { + return this.index == 0; + } + /** * Back up one character. This provides a sort of lookahead capability, * so that you can test for a digit or letter before attempting to parse @@ -458,14 +467,14 @@ public Object nextValue() throws JSONException { case '{': this.back(); try { - return new JSONObject(this, jsonParserConfiguration); + return new JSONObject(this, jsonParserConfiguration, false); } catch (StackOverflowError e) { throw new JSONException("JSON Array or Object depth too large to process.", e); } case '[': this.back(); try { - return new JSONArray(this, jsonParserConfiguration); + return new JSONArray(this, jsonParserConfiguration, false); } catch (StackOverflowError e) { throw new JSONException("JSON Array or Object depth too large to process.", e); } diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index c54b61795..ad22d9615 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -1566,4 +1566,22 @@ public void TestLenientCommas() { "[1,null,3]", jsonArray.toString()); } } + + @Test + public void strictModeShouldCheckTrailingCharactersAfterNextAndBack() { + JSONParserConfiguration strict = + new JSONParserConfiguration().withStrictMode(); + + JSONTokener tok = new JSONTokener("[]xxx"); + + tok.next(); + tok.back(); + + JSONException exception = assertThrows( + JSONException.class, + () -> new JSONArray(tok, strict)); + + assertTrue(exception.getMessage().contains( + "Unparsed characters found at end of input text")); + } } diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 6b692789e..8c40fc7c3 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -4337,4 +4337,22 @@ public void testStringToNumberInvalidFormats() { } } + @Test + public void strictModeShouldCheckTrailingCharactersAfterNextAndBack() { + JSONParserConfiguration strict = + new JSONParserConfiguration().withStrictMode(); + + JSONTokener tok = new JSONTokener("{}xxx"); + + tok.next(); + tok.back(); + + JSONException exception = assertThrows( + JSONException.class, + () -> new JSONObject(tok, strict)); + + assertTrue(exception.getMessage().contains( + "Unparsed characters found at end of input text")); + } + } From 359b43d8dfed7395d155bdd7b69fe9bafbac7fd1 Mon Sep 17 00:00:00 2001 From: XIAYM-gh Date: Fri, 4 Sep 2026 08:09:14 +0800 Subject: [PATCH 16/33] Apply corner-case fixes under instruction --- src/main/java/org/json/JSONArray.java | 10 +++--- src/main/java/org/json/JSONObject.java | 18 +++++----- src/main/java/org/json/JSONTokener.java | 21 +++++++++--- .../java/org/json/junit/JSONArrayTest.java | 34 +++++++++++++++++++ .../java/org/json/junit/JSONObjectTest.java | 33 ++++++++++++++++++ 5 files changed, 98 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/json/JSONArray.java b/src/main/java/org/json/JSONArray.java index 62eca71fe..d5fb170e9 100644 --- a/src/main/java/org/json/JSONArray.java +++ b/src/main/java/org/json/JSONArray.java @@ -80,7 +80,7 @@ public JSONArray() { * @param x * A JSONTokener * @throws JSONException - * If there is a syntax error. + * If there is a syntax error. */ public JSONArray(JSONTokener x) throws JSONException { this(x, x.getJsonParserConfiguration()); @@ -103,10 +103,10 @@ public JSONArray(JSONTokener x, JSONParserConfiguration jsonParserConfiguration) * * @param x A JSONTokener instance from which the JSONArray is constructed. * @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser. - * @param eofRequired A boolean that determines whether this array is the root. + * @param isInitial A boolean that determines whether this array is the root. * @throws JSONException If a syntax error occurs during the construction of the JSONArray. */ - JSONArray(JSONTokener x, JSONParserConfiguration jsonParserConfiguration, boolean eofRequired) throws JSONException { + JSONArray(JSONTokener x, JSONParserConfiguration jsonParserConfiguration, boolean isInitial) throws JSONException { this(); if (x.nextClean() != '[') { @@ -130,10 +130,10 @@ public JSONArray(JSONTokener x, JSONParserConfiguration jsonParserConfiguration) x.back(); this.myArrayList.add(x.nextValue()); } - if (checkForSyntaxError(x, jsonParserConfiguration, eofRequired)) return; + if (checkForSyntaxError(x, jsonParserConfiguration, isInitial)) return; } } else { - if (eofRequired && jsonParserConfiguration.isStrictMode() && x.nextClean() != 0) { + if (isInitial && jsonParserConfiguration.isStrictMode() && x.nextClean() != 0) { throw x.syntaxError("Strict mode error: Unparsed characters found at end of input text"); } } diff --git a/src/main/java/org/json/JSONObject.java b/src/main/java/org/json/JSONObject.java index fcce72ab7..295dea4b6 100644 --- a/src/main/java/org/json/JSONObject.java +++ b/src/main/java/org/json/JSONObject.java @@ -195,8 +195,8 @@ public JSONObject(JSONObject jo, String ... names) { * @param x * A JSONTokener object containing the source string. * @throws JSONException - * If there is a syntax error in the source string or a - * duplicated key. + * If there is a syntax error in the source string or a + * duplicated key. */ public JSONObject(JSONTokener x) throws JSONException { this(x, x.getJsonParserConfiguration()); @@ -210,8 +210,8 @@ public JSONObject(JSONTokener x) throws JSONException { * @param jsonParserConfiguration * Variable to pass parser custom configuration for json parsing. * @throws JSONException - * If there is a syntax error in the source string or a - * duplicated key. + * If there is a syntax error in the source string or a + * duplicated key. */ public JSONObject(JSONTokener x, JSONParserConfiguration jsonParserConfiguration) throws JSONException { this(x, jsonParserConfiguration, x.isAtStart()); @@ -225,20 +225,20 @@ public JSONObject(JSONTokener x, JSONParserConfiguration jsonParserConfiguration * A JSONTokener object containing the source string. * @param jsonParserConfiguration * Variable to pass parser custom configuration for json parsing. - * @param eofRequired + * @param isInitial * A boolean that determines whether this object is the root. * @throws JSONException - * If there is a syntax error in the source string or a - * duplicated key. + * If there is a syntax error in the source string or a + * duplicated key. */ - JSONObject(JSONTokener x, JSONParserConfiguration jsonParserConfiguration, boolean eofRequired) throws JSONException { + JSONObject(JSONTokener x, JSONParserConfiguration jsonParserConfiguration, boolean isInitial) throws JSONException { this(); if (x.nextClean() != '{') { throw x.syntaxError("A JSONObject text must begin with '{'"); } for (;;) { - if (parseJSONObject(x, jsonParserConfiguration, eofRequired)) { + if (parseJSONObject(x, jsonParserConfiguration, isInitial)) { return; } } diff --git a/src/main/java/org/json/JSONTokener.java b/src/main/java/org/json/JSONTokener.java index e8ae9fcf1..2eaeedee8 100644 --- a/src/main/java/org/json/JSONTokener.java +++ b/src/main/java/org/json/JSONTokener.java @@ -31,6 +31,8 @@ public class JSONTokener { private boolean usePrevious; /** the number of characters read in the previous line. */ private long characterPreviousLine; + /** number of non-whitespace characters read from the source. */ + private long contentCharCount; // access to this object is required for strict mode checking private JSONParserConfiguration jsonParserConfiguration; @@ -60,6 +62,7 @@ public JSONTokener(Reader reader, JSONParserConfiguration jsonParserConfiguratio this.usePrevious = false; this.previous = 0; this.index = 0; + this.contentCharCount = 0; this.character = 1; this.characterPreviousLine = 0; this.line = 1; @@ -121,12 +124,14 @@ public void setJsonParserConfiguration(JSONParserConfiguration jsonParserConfigu } /** - * Returns whether the tokener is currently positioned at the beginning, + * Returns whether the tokener is positioned at the beginning, + * i.e. only whitespace characters (or no characters at all) have been read so far. + * Consuming and backing up over the first characters does not change the result. * - * @return true if the current input position is the beginning + * @return true if no non-whitespace character has been read */ - public boolean isAtStart() { - return this.index == 0; + protected boolean isAtStart() { + return this.contentCharCount == 0; } /** @@ -140,6 +145,9 @@ public void back() throws JSONException { if (this.usePrevious || this.index <= 0) { throw new JSONException("Stepping back two steps is not supported"); } + if (this.previous > ' ') { + this.contentCharCount--; + } this.decrementIndexes(); this.usePrevious = true; this.eof = false; @@ -240,6 +248,9 @@ public char next() throws JSONException { return 0; } this.incrementIndexes(c); + if (c > ' ') { + this.contentCharCount++; + } this.previous = (char) c; return this.previous; } @@ -558,6 +569,7 @@ public char skipTo(char to) throws JSONException { long startIndex = this.index; long startCharacter = this.character; long startLine = this.line; + long startContentCharCount = this.contentCharCount; this.reader.mark(1000000); do { c = this.next(); @@ -569,6 +581,7 @@ public char skipTo(char to) throws JSONException { this.index = startIndex; this.character = startCharacter; this.line = startLine; + this.contentCharCount = startContentCharCount; return 0; } } while (c != to); diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index ad22d9615..e59b2e19d 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -1573,7 +1573,24 @@ public void strictModeShouldCheckTrailingCharactersAfterNextAndBack() { new JSONParserConfiguration().withStrictMode(); JSONTokener tok = new JSONTokener("[]xxx"); + tok.next(); + tok.back(); + + JSONException exception = assertThrows( + JSONException.class, + () -> new JSONArray(tok, strict)); + assertTrue(exception.getMessage().contains( + "Unparsed characters found at end of input text")); + } + + @Test + public void strictModeShouldCheckTrailingCharactersAfterConsumedWhitespace() { + JSONParserConfiguration strict = + new JSONParserConfiguration().withStrictMode(); + + JSONTokener tok = new JSONTokener(" []xxx"); + tok.next(); tok.next(); tok.back(); @@ -1584,4 +1601,21 @@ public void strictModeShouldCheckTrailingCharactersAfterNextAndBack() { assertTrue(exception.getMessage().contains( "Unparsed characters found at end of input text")); } + + @Test + public void strictModeShouldCheckTrailingCharactersAfterNextCleanAndBack() { + JSONParserConfiguration strict = + new JSONParserConfiguration().withStrictMode(); + + JSONTokener tok = new JSONTokener(" []xxx"); + tok.nextClean(); + tok.back(); + + JSONException exception = assertThrows( + JSONException.class, + () -> new JSONArray(tok, strict)); + + assertTrue(exception.getMessage().contains( + "Unparsed characters found at end of input text")); + } } diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 8c40fc7c3..a0f0638b0 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -4343,7 +4343,24 @@ public void strictModeShouldCheckTrailingCharactersAfterNextAndBack() { new JSONParserConfiguration().withStrictMode(); JSONTokener tok = new JSONTokener("{}xxx"); + tok.next(); + tok.back(); + + JSONException exception = assertThrows( + JSONException.class, + () -> new JSONObject(tok, strict)); + + assertTrue(exception.getMessage().contains( + "Unparsed characters found at end of input text")); + } + + @Test + public void strictModeShouldCheckTrailingCharactersAfterConsumedWhitespace() { + JSONParserConfiguration strict = + new JSONParserConfiguration().withStrictMode(); + JSONTokener tok = new JSONTokener(" {}xxx"); + tok.next(); tok.next(); tok.back(); @@ -4355,4 +4372,20 @@ public void strictModeShouldCheckTrailingCharactersAfterNextAndBack() { "Unparsed characters found at end of input text")); } + @Test + public void strictModeShouldCheckTrailingCharactersAfterNextCleanAndBack() { + JSONParserConfiguration strict = + new JSONParserConfiguration().withStrictMode(); + + JSONTokener tok = new JSONTokener(" {}xxx"); + tok.nextClean(); + tok.back(); + + JSONException exception = assertThrows( + JSONException.class, + () -> new JSONObject(tok, strict)); + + assertTrue(exception.getMessage().contains( + "Unparsed characters found at end of input text")); + } } From a25f83a0e4301d1ab146ab69b57b1521d32ca6bd Mon Sep 17 00:00:00 2001 From: XIAYM-gh Date: Thu, 10 Sep 2026 17:47:29 +0800 Subject: [PATCH 17/33] Strip JSONTokener#isAtStart() --- src/main/java/org/json/JSONArray.java | 2 +- src/main/java/org/json/JSONObject.java | 2 +- src/main/java/org/json/JSONTokener.java | 22 ---------------------- 3 files changed, 2 insertions(+), 24 deletions(-) diff --git a/src/main/java/org/json/JSONArray.java b/src/main/java/org/json/JSONArray.java index d5fb170e9..2bd80c1d2 100644 --- a/src/main/java/org/json/JSONArray.java +++ b/src/main/java/org/json/JSONArray.java @@ -94,7 +94,7 @@ public JSONArray(JSONTokener x) throws JSONException { * @throws JSONException If a syntax error occurs during the construction of the JSONArray. */ public JSONArray(JSONTokener x, JSONParserConfiguration jsonParserConfiguration) throws JSONException { - this(x, jsonParserConfiguration, x.isAtStart()); + this(x, jsonParserConfiguration, true); } /** diff --git a/src/main/java/org/json/JSONObject.java b/src/main/java/org/json/JSONObject.java index 295dea4b6..0b2268caa 100644 --- a/src/main/java/org/json/JSONObject.java +++ b/src/main/java/org/json/JSONObject.java @@ -214,7 +214,7 @@ public JSONObject(JSONTokener x) throws JSONException { * duplicated key. */ public JSONObject(JSONTokener x, JSONParserConfiguration jsonParserConfiguration) throws JSONException { - this(x, jsonParserConfiguration, x.isAtStart()); + this(x, jsonParserConfiguration, true); } /** diff --git a/src/main/java/org/json/JSONTokener.java b/src/main/java/org/json/JSONTokener.java index 2eaeedee8..60660b020 100644 --- a/src/main/java/org/json/JSONTokener.java +++ b/src/main/java/org/json/JSONTokener.java @@ -31,8 +31,6 @@ public class JSONTokener { private boolean usePrevious; /** the number of characters read in the previous line. */ private long characterPreviousLine; - /** number of non-whitespace characters read from the source. */ - private long contentCharCount; // access to this object is required for strict mode checking private JSONParserConfiguration jsonParserConfiguration; @@ -62,7 +60,6 @@ public JSONTokener(Reader reader, JSONParserConfiguration jsonParserConfiguratio this.usePrevious = false; this.previous = 0; this.index = 0; - this.contentCharCount = 0; this.character = 1; this.characterPreviousLine = 0; this.line = 1; @@ -123,17 +120,6 @@ public void setJsonParserConfiguration(JSONParserConfiguration jsonParserConfigu this.jsonParserConfiguration = jsonParserConfiguration; } - /** - * Returns whether the tokener is positioned at the beginning, - * i.e. only whitespace characters (or no characters at all) have been read so far. - * Consuming and backing up over the first characters does not change the result. - * - * @return true if no non-whitespace character has been read - */ - protected boolean isAtStart() { - return this.contentCharCount == 0; - } - /** * Back up one character. This provides a sort of lookahead capability, * so that you can test for a digit or letter before attempting to parse @@ -145,9 +131,6 @@ public void back() throws JSONException { if (this.usePrevious || this.index <= 0) { throw new JSONException("Stepping back two steps is not supported"); } - if (this.previous > ' ') { - this.contentCharCount--; - } this.decrementIndexes(); this.usePrevious = true; this.eof = false; @@ -248,9 +231,6 @@ public char next() throws JSONException { return 0; } this.incrementIndexes(c); - if (c > ' ') { - this.contentCharCount++; - } this.previous = (char) c; return this.previous; } @@ -569,7 +549,6 @@ public char skipTo(char to) throws JSONException { long startIndex = this.index; long startCharacter = this.character; long startLine = this.line; - long startContentCharCount = this.contentCharCount; this.reader.mark(1000000); do { c = this.next(); @@ -581,7 +560,6 @@ public char skipTo(char to) throws JSONException { this.index = startIndex; this.character = startCharacter; this.line = startLine; - this.contentCharCount = startContentCharCount; return 0; } } while (c != to); From 0ae8d5ab4f19d20bbfe0ba02c62a1df9243f8d31 Mon Sep 17 00:00:00 2001 From: sajad mahmoodifar Date: Fri, 18 Sep 2026 13:25:36 +0330 Subject: [PATCH 18/33] fix: apply explicit parser configuration Fixes #945 --- src/main/java/org/json/JSONArray.java | 3 ++ src/main/java/org/json/JSONObject.java | 3 ++ .../junit/JSONParserConfigurationTest.java | 51 +++++++++++++++++++ 3 files changed, 57 insertions(+) diff --git a/src/main/java/org/json/JSONArray.java b/src/main/java/org/json/JSONArray.java index 2bd80c1d2..a0934e6d9 100644 --- a/src/main/java/org/json/JSONArray.java +++ b/src/main/java/org/json/JSONArray.java @@ -88,6 +88,8 @@ public JSONArray(JSONTokener x) throws JSONException { /** * Constructs a JSONArray from a JSONTokener and a JSONParserConfiguration. + * The supplied configuration replaces the tokener's configuration and applies + * to all values, including nested objects and arrays. * * @param x A JSONTokener instance from which the JSONArray is constructed. * @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser. @@ -108,6 +110,7 @@ public JSONArray(JSONTokener x, JSONParserConfiguration jsonParserConfiguration) */ JSONArray(JSONTokener x, JSONParserConfiguration jsonParserConfiguration, boolean isInitial) throws JSONException { this(); + x.setJsonParserConfiguration(jsonParserConfiguration); if (x.nextClean() != '[') { throw x.syntaxError("A JSONArray text must start with '['"); diff --git a/src/main/java/org/json/JSONObject.java b/src/main/java/org/json/JSONObject.java index 0b2268caa..77571f73d 100644 --- a/src/main/java/org/json/JSONObject.java +++ b/src/main/java/org/json/JSONObject.java @@ -204,6 +204,8 @@ public JSONObject(JSONTokener x) throws JSONException { /** * Construct a JSONObject from a JSONTokener with custom json parse configurations. + * The supplied configuration replaces the tokener's configuration and applies + * to all values, including nested objects and arrays. * * @param x * A JSONTokener object containing the source string. @@ -233,6 +235,7 @@ public JSONObject(JSONTokener x, JSONParserConfiguration jsonParserConfiguration */ JSONObject(JSONTokener x, JSONParserConfiguration jsonParserConfiguration, boolean isInitial) throws JSONException { this(); + x.setJsonParserConfiguration(jsonParserConfiguration); if (x.nextClean() != '{') { throw x.syntaxError("A JSONObject text must begin with '{'"); diff --git a/src/test/java/org/json/junit/JSONParserConfigurationTest.java b/src/test/java/org/json/junit/JSONParserConfigurationTest.java index 926c49f41..cbe44474e 100644 --- a/src/test/java/org/json/junit/JSONParserConfigurationTest.java +++ b/src/test/java/org/json/junit/JSONParserConfigurationTest.java @@ -16,6 +16,7 @@ import java.util.stream.Stream; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -36,6 +37,56 @@ public void testOverwrite() { assertEquals("duplicate key should be overwritten", "value2", jsonObject.getString("key")); } + @Test + public void objectConstructorAppliesExplicitStrictModeToValues() { + JSONParserConfiguration configuration = new JSONParserConfiguration().withStrictMode(); + JSONParserConfiguration lenient = new JSONParserConfiguration().withStrictMode(false); + for (String source : Arrays.asList( + "{\"value\":'text'}", + "{\"value\":[1,]}", + "{\"value\":{\"nested\":1,}}")) { + assertThrows(JSONException.class, () -> new JSONObject(new JSONTokener(source, lenient), configuration)); + } + } + + @Test + public void arrayConstructorAppliesExplicitStrictModeToValues() { + JSONParserConfiguration configuration = new JSONParserConfiguration().withStrictMode(); + JSONParserConfiguration lenient = new JSONParserConfiguration().withStrictMode(false); + for (String source : Arrays.asList( + "['text']", + "[[1,]]", + "[{\"nested\":1,}]")) { + assertThrows(JSONException.class, () -> new JSONArray(new JSONTokener(source, lenient), configuration)); + } + } + + @Test + public void explicitConfigurationOverridesTokenerStrictMode() { + JSONParserConfiguration strict = new JSONParserConfiguration().withStrictMode(); + JSONParserConfiguration lenient = new JSONParserConfiguration().withStrictMode(false); + JSONTokener objectTokener = new JSONTokener("{\"value\":[{'nested':'text',}]}", strict); + JSONTokener arrayTokener = new JSONTokener("[{\"value\":['text',]}]", strict); + + JSONObject object = new JSONObject(objectTokener, lenient); + JSONArray array = new JSONArray(arrayTokener, lenient); + + assertEquals("text", object.getJSONArray("value").getJSONObject(0).getString("nested")); + assertEquals("text", array.getJSONObject(0).getJSONArray("value").getString(0)); + assertSame(lenient, objectTokener.getJsonParserConfiguration()); + assertSame(lenient, arrayTokener.getJsonParserConfiguration()); + } + + @Test + public void explicitConfigurationAppliesToNestedDuplicateKeys() { + JSONParserConfiguration configuration = new JSONParserConfiguration().withOverwriteDuplicateKey(true); + JSONObject object = new JSONObject(new JSONTokener("{\"value\":[{\"key\":1,\"key\":2}]}"), configuration); + JSONArray array = new JSONArray(new JSONTokener("[{\"value\":{\"key\":1,\"key\":2}}]"), configuration); + + assertEquals(2, object.getJSONArray("value").getJSONObject(0).getInt("key")); + assertEquals(2, array.getJSONObject(0).getJSONObject("value").getInt("key")); + } + @Test public void strictModeIsCloned(){ JSONParserConfiguration jsonParserConfiguration = new JSONParserConfiguration() From 9f3b527d9f615205ad12530813d74d368c41c2bf Mon Sep 17 00:00:00 2001 From: sajad mahmoodifar Date: Fri, 18 Sep 2026 16:53:59 +0330 Subject: [PATCH 19/33] fix: restore tokener configuration after parsing --- src/main/java/org/json/JSONArray.java | 61 ++++++++++--------- src/main/java/org/json/JSONObject.java | 25 +++++--- src/main/java/org/json/JSONTokener.java | 4 ++ .../junit/JSONParserConfigurationTest.java | 48 +++++++++++++-- 4 files changed, 94 insertions(+), 44 deletions(-) diff --git a/src/main/java/org/json/JSONArray.java b/src/main/java/org/json/JSONArray.java index a0934e6d9..ff25580e4 100644 --- a/src/main/java/org/json/JSONArray.java +++ b/src/main/java/org/json/JSONArray.java @@ -88,8 +88,9 @@ public JSONArray(JSONTokener x) throws JSONException { /** * Constructs a JSONArray from a JSONTokener and a JSONParserConfiguration. - * The supplied configuration replaces the tokener's configuration and applies - * to all values, including nested objects and arrays. + * The supplied configuration applies to all values during construction, + * including nested objects and arrays. The tokener's original configuration + * is restored afterward, even if parsing fails. * * @param x A JSONTokener instance from which the JSONArray is constructed. * @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser. @@ -110,35 +111,39 @@ public JSONArray(JSONTokener x, JSONParserConfiguration jsonParserConfiguration) */ JSONArray(JSONTokener x, JSONParserConfiguration jsonParserConfiguration, boolean isInitial) throws JSONException { this(); - x.setJsonParserConfiguration(jsonParserConfiguration); - - if (x.nextClean() != '[') { - throw x.syntaxError("A JSONArray text must start with '['"); - } + JSONParserConfiguration originalConfiguration = x.getJsonParserConfiguration(); + x.setJsonParserConfigurationInternal(jsonParserConfiguration); + try { + if (x.nextClean() != '[') { + throw x.syntaxError("A JSONArray text must start with '['"); + } - char nextChar = x.nextClean(); - if (nextChar == 0) { - // array is unclosed. No ']' found, instead EOF - throw x.syntaxError("Expected a ',' or ']'"); - } else if (nextChar==',' && jsonParserConfiguration.isStrictMode()) { - throw x.syntaxError("Array content starts with a ','"); - } - if (nextChar != ']') { - x.back(); - for (;;) { - if (x.nextClean() == ',') { - x.back(); - this.myArrayList.add(JSONObject.NULL); - } else { - x.back(); - this.myArrayList.add(x.nextValue()); - } - if (checkForSyntaxError(x, jsonParserConfiguration, isInitial)) return; + char nextChar = x.nextClean(); + if (nextChar == 0) { + // array is unclosed. No ']' found, instead EOF + throw x.syntaxError("Expected a ',' or ']'"); + } else if (nextChar==',' && jsonParserConfiguration.isStrictMode()) { + throw x.syntaxError("Array content starts with a ','"); } - } else { - if (isInitial && jsonParserConfiguration.isStrictMode() && x.nextClean() != 0) { - throw x.syntaxError("Strict mode error: Unparsed characters found at end of input text"); + if (nextChar != ']') { + x.back(); + for (;;) { + if (x.nextClean() == ',') { + x.back(); + this.myArrayList.add(JSONObject.NULL); + } else { + x.back(); + this.myArrayList.add(x.nextValue()); + } + if (checkForSyntaxError(x, jsonParserConfiguration, isInitial)) return; + } + } else { + if (isInitial && jsonParserConfiguration.isStrictMode() && x.nextClean() != 0) { + throw x.syntaxError("Strict mode error: Unparsed characters found at end of input text"); + } } + } finally { + x.setJsonParserConfigurationInternal(originalConfiguration); } } diff --git a/src/main/java/org/json/JSONObject.java b/src/main/java/org/json/JSONObject.java index 77571f73d..3ded23f61 100644 --- a/src/main/java/org/json/JSONObject.java +++ b/src/main/java/org/json/JSONObject.java @@ -204,8 +204,9 @@ public JSONObject(JSONTokener x) throws JSONException { /** * Construct a JSONObject from a JSONTokener with custom json parse configurations. - * The supplied configuration replaces the tokener's configuration and applies - * to all values, including nested objects and arrays. + * The supplied configuration applies to all values during construction, + * including nested objects and arrays. The tokener's original configuration + * is restored afterward, even if parsing fails. * * @param x * A JSONTokener object containing the source string. @@ -235,15 +236,19 @@ public JSONObject(JSONTokener x, JSONParserConfiguration jsonParserConfiguration */ JSONObject(JSONTokener x, JSONParserConfiguration jsonParserConfiguration, boolean isInitial) throws JSONException { this(); - x.setJsonParserConfiguration(jsonParserConfiguration); - - if (x.nextClean() != '{') { - throw x.syntaxError("A JSONObject text must begin with '{'"); - } - for (;;) { - if (parseJSONObject(x, jsonParserConfiguration, isInitial)) { - return; + JSONParserConfiguration originalConfiguration = x.getJsonParserConfiguration(); + x.setJsonParserConfigurationInternal(jsonParserConfiguration); + try { + if (x.nextClean() != '{') { + throw x.syntaxError("A JSONObject text must begin with '{'"); + } + for (;;) { + if (parseJSONObject(x, jsonParserConfiguration, isInitial)) { + return; + } } + } finally { + x.setJsonParserConfigurationInternal(originalConfiguration); } } diff --git a/src/main/java/org/json/JSONTokener.java b/src/main/java/org/json/JSONTokener.java index 60660b020..1acb73bf7 100644 --- a/src/main/java/org/json/JSONTokener.java +++ b/src/main/java/org/json/JSONTokener.java @@ -117,6 +117,10 @@ public JSONParserConfiguration getJsonParserConfiguration() { */ @Deprecated public void setJsonParserConfiguration(JSONParserConfiguration jsonParserConfiguration) { + setJsonParserConfigurationInternal(jsonParserConfiguration); + } + + void setJsonParserConfigurationInternal(JSONParserConfiguration jsonParserConfiguration) { this.jsonParserConfiguration = jsonParserConfiguration; } diff --git a/src/test/java/org/json/junit/JSONParserConfigurationTest.java b/src/test/java/org/json/junit/JSONParserConfigurationTest.java index cbe44474e..21bb84115 100644 --- a/src/test/java/org/json/junit/JSONParserConfigurationTest.java +++ b/src/test/java/org/json/junit/JSONParserConfigurationTest.java @@ -42,10 +42,15 @@ public void objectConstructorAppliesExplicitStrictModeToValues() { JSONParserConfiguration configuration = new JSONParserConfiguration().withStrictMode(); JSONParserConfiguration lenient = new JSONParserConfiguration().withStrictMode(false); for (String source : Arrays.asList( + "[]", + "{", + "{} trailing", "{\"value\":'text'}", "{\"value\":[1,]}", "{\"value\":{\"nested\":1,}}")) { - assertThrows(JSONException.class, () -> new JSONObject(new JSONTokener(source, lenient), configuration)); + JSONTokener tokener = new JSONTokener(source, lenient); + assertThrows(JSONException.class, () -> new JSONObject(tokener, configuration)); + assertSame(lenient, tokener.getJsonParserConfiguration()); } } @@ -54,10 +59,15 @@ public void arrayConstructorAppliesExplicitStrictModeToValues() { JSONParserConfiguration configuration = new JSONParserConfiguration().withStrictMode(); JSONParserConfiguration lenient = new JSONParserConfiguration().withStrictMode(false); for (String source : Arrays.asList( + "{}", + "[", + "[] trailing", "['text']", "[[1,]]", "[{\"nested\":1,}]")) { - assertThrows(JSONException.class, () -> new JSONArray(new JSONTokener(source, lenient), configuration)); + JSONTokener tokener = new JSONTokener(source, lenient); + assertThrows(JSONException.class, () -> new JSONArray(tokener, configuration)); + assertSame(lenient, tokener.getJsonParserConfiguration()); } } @@ -65,16 +75,42 @@ public void arrayConstructorAppliesExplicitStrictModeToValues() { public void explicitConfigurationOverridesTokenerStrictMode() { JSONParserConfiguration strict = new JSONParserConfiguration().withStrictMode(); JSONParserConfiguration lenient = new JSONParserConfiguration().withStrictMode(false); - JSONTokener objectTokener = new JSONTokener("{\"value\":[{'nested':'text',}]}", strict); - JSONTokener arrayTokener = new JSONTokener("[{\"value\":['text',]}]", strict); + JSONTokener objectTokener = new JSONTokener("{\"value\":[{'nested':'text',}], 'other':'text'} 'next'", strict); + JSONTokener arrayTokener = new JSONTokener("[{\"value\":['text',]},'text'] 'next'", strict); JSONObject object = new JSONObject(objectTokener, lenient); JSONArray array = new JSONArray(arrayTokener, lenient); assertEquals("text", object.getJSONArray("value").getJSONObject(0).getString("nested")); assertEquals("text", array.getJSONObject(0).getJSONArray("value").getString(0)); - assertSame(lenient, objectTokener.getJsonParserConfiguration()); - assertSame(lenient, arrayTokener.getJsonParserConfiguration()); + assertEquals("text", object.getString("other")); + assertEquals("text", array.getString(1)); + assertSame(strict, objectTokener.getJsonParserConfiguration()); + assertSame(strict, arrayTokener.getJsonParserConfiguration()); + assertThrows(JSONException.class, () -> objectTokener.nextValue()); + assertThrows(JSONException.class, () -> arrayTokener.nextValue()); + } + + @Test + public void objectConstructorRestoresTokenerConfiguration() { + JSONParserConfiguration original = new JSONParserConfiguration().withStrictMode(false); + JSONParserConfiguration strict = new JSONParserConfiguration().withStrictMode(); + for (String source : Arrays.asList("{}", "{\"value\":[{\"nested\":\"text\"}],\"other\":true}")) { + JSONTokener tokener = new JSONTokener(source, original); + new JSONObject(tokener, strict); + assertSame(original, tokener.getJsonParserConfiguration()); + } + } + + @Test + public void arrayConstructorRestoresTokenerConfiguration() { + JSONParserConfiguration original = new JSONParserConfiguration().withStrictMode(false); + JSONParserConfiguration strict = new JSONParserConfiguration().withStrictMode(); + for (String source : Arrays.asList("[]", "[{\"value\":[\"text\"]},true]")) { + JSONTokener tokener = new JSONTokener(source, original); + new JSONArray(tokener, strict); + assertSame(original, tokener.getJsonParserConfiguration()); + } } @Test From 775c98ea41a5236751f7284e76e3b9b4e5df5a0b Mon Sep 17 00:00:00 2001 From: Jake Wang Date: Fri, 18 Sep 2026 20:10:16 -0400 Subject: [PATCH 20/33] Avoid decoding JSON Pointer tokens twice --- src/main/java/org/json/JSONPointer.java | 2 +- .../java/org/json/junit/JSONPointerTest.java | 26 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/json/JSONPointer.java b/src/main/java/org/json/JSONPointer.java index 34066c1aa..f4cff541c 100644 --- a/src/main/java/org/json/JSONPointer.java +++ b/src/main/java/org/json/JSONPointer.java @@ -203,7 +203,7 @@ public Object queryFrom(Object document) throws JSONPointerException { Object current = document; for (String token : this.refTokens) { if (current instanceof JSONObject) { - current = ((JSONObject) current).opt(unescape(token)); + current = ((JSONObject) current).opt(token); } else if (current instanceof JSONArray) { current = readByIndexToken(current, token); } else { diff --git a/src/test/java/org/json/junit/JSONPointerTest.java b/src/test/java/org/json/junit/JSONPointerTest.java index a420b297f..bbea5d2a3 100644 --- a/src/test/java/org/json/junit/JSONPointerTest.java +++ b/src/test/java/org/json/junit/JSONPointerTest.java @@ -98,6 +98,32 @@ public void tildeEscaping() { assertEquals(8, query("/m~0n")); } + @Test + public void escapeSequencesInObjectKeys() { + JSONObject object = new JSONObject().put("~1", "tilde one").put("/", "slash") + .put("~0", "tilde zero").put("~", "tilde"); + assertEquals("tilde one", object.query("/~01")); + assertEquals("tilde zero", object.query("/~00")); + assertEquals("tilde one", object.query("#/~01")); + assertEquals("tilde zero", object.query("#/~00")); + } + + @Test + public void builderPreservesLiteralTokens() { + JSONObject object = new JSONObject().put("~1", "tilde one").put("/", "slash") + .put("~0", "tilde zero").put("~", "tilde"); + assertEquals("tilde one", JSONPointer.builder().append("~1").build().queryFrom(object)); + assertEquals("tilde zero", JSONPointer.builder().append("~0").build().queryFrom(object)); + } + + @Test + public void tokenListPreservesLiteralTokens() { + JSONObject object = new JSONObject().put("~1", "tilde one").put("/", "slash") + .put("~0", "tilde zero").put("~", "tilde"); + assertEquals("tilde one", new JSONPointer(java.util.Arrays.asList("~1")).queryFrom(object)); + assertEquals("tilde zero", new JSONPointer(java.util.Arrays.asList("~0")).queryFrom(object)); + } + /** * We pass backslashes as-is * From f875ab2fc781ad77a12f35a74d8345e836bb5dfe Mon Sep 17 00:00:00 2001 From: Denys Khalitov <187554832+DarkLight606@users.noreply.github.com> Date: Sat, 26 Sep 2026 17:19:47 +0300 Subject: [PATCH 21/33] Escape ~ and / in JSONPointer.toURIFragment() toURIFragment() URL-encoded each reference token but skipped the ~0/~1 escaping from RFC 6901. Tokens are stored as literal key names, so a key containing / or ~ produced a fragment that parsed back to a different pointer. Apply escape() before encoding, as toString() already does. Fixes #1082 --- src/main/java/org/json/JSONPointer.java | 2 +- .../java/org/json/junit/JSONPointerTest.java | 24 +++++++++++++++++-- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/json/JSONPointer.java b/src/main/java/org/json/JSONPointer.java index f4cff541c..83a0690d7 100644 --- a/src/main/java/org/json/JSONPointer.java +++ b/src/main/java/org/json/JSONPointer.java @@ -276,7 +276,7 @@ public String toURIFragment() { try { StringBuilder rval = new StringBuilder("#"); for (String token : this.refTokens) { - rval.append('/').append(URLEncoder.encode(token, ENCODING)); + rval.append('/').append(URLEncoder.encode(escape(token), ENCODING)); } return rval.toString(); } catch (UnsupportedEncodingException e) { diff --git a/src/test/java/org/json/junit/JSONPointerTest.java b/src/test/java/org/json/junit/JSONPointerTest.java index bbea5d2a3..7095d45da 100644 --- a/src/test/java/org/json/junit/JSONPointerTest.java +++ b/src/test/java/org/json/junit/JSONPointerTest.java @@ -219,9 +219,29 @@ public void toURIFragment() { assertEquals("#/c%25d", new JSONPointer("/c%d").toURIFragment()); assertEquals("#/e%5Ef", new JSONPointer("/e^f").toURIFragment()); assertEquals("#/g%7Ch", new JSONPointer("/g|h").toURIFragment()); - assertEquals("#/m%7En", new JSONPointer("/m~n").toURIFragment()); + assertEquals("#/m%7E0n", new JSONPointer("/m~n").toURIFragment()); } - + + @Test + public void toURIFragmentEscaping() { + JSONPointer pointer = JSONPointer.builder() + .append("obj") + .append("other~key").append("another/key") + .append(0) + .build(); + assertEquals("#/obj/other%7E0key/another%7E1key/0", pointer.toURIFragment()); + assertEquals("val", new JSONPointer(pointer.toURIFragment()).queryFrom(document)); + } + + @Test + public void toURIFragmentRoundTrip() { + JSONObject object = new JSONObject().put("~1", "tilde one").put("/", "slash"); + JSONPointer tildeOne = JSONPointer.builder().append("~1").build(); + JSONPointer slash = JSONPointer.builder().append("/").build(); + assertEquals("tilde one", object.query(tildeOne.toURIFragment())); + assertEquals("slash", object.query(slash.toURIFragment())); + } + @Test public void tokenListIsCopiedInConstructor() { JSONPointer.Builder b = JSONPointer.builder().append("key1"); From 5dfa60ba0adc1243d90fb87517a6cc236154db83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=95=88=EC=8A=B9=ED=98=84?= Date: Thu, 1 Oct 2026 16:55:38 +0900 Subject: [PATCH 22/33] Fix reserved childNodes attribute check in JSONML JSONML object-form parsing uses "childNodes" to store child elements, but the reserved-attribute check incorrectly used "childNode". This rejected ordinary "childNode" attributes while accepting "childNodes" attributes, whose values could then be overwritten by the element's children. Correct the reserved-attribute check to use "childNodes" and add JUnit 4 regression tests covering: - Rejection of reserved "childNodes" attributes in object-form parsing - Preservation of ordinary "childNode" attributes and child content - Continued rejection of reserved "tagName" attributes - Preservation of both attribute names in array-form parsing Verify each scenario with keepStrings enabled and disabled. Validation: - All 40 JSONML tests pass - Full test suite: 807 passed, 6 skipped on Java 11 with Gradle 8.13 - Both bug regression tests fail against the original implementation Fixes #1080 --- src/main/java/org/json/JSONML.java | 2 +- src/test/java/org/json/junit/JSONMLTest.java | 57 ++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/json/JSONML.java b/src/main/java/org/json/JSONML.java index 6ec997061..27fe2d509 100644 --- a/src/main/java/org/json/JSONML.java +++ b/src/main/java/org/json/JSONML.java @@ -205,7 +205,7 @@ private static Object parse( // attribute = value attribute = (String)token; - if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) { + if (!arrayForm && ("tagName".equals(attribute) || "childNodes".equals(attribute))) { throw x.syntaxError("Reserved attribute."); } token = x.nextToken(); diff --git a/src/test/java/org/json/junit/JSONMLTest.java b/src/test/java/org/json/junit/JSONMLTest.java index 93a6821d8..c83f73e24 100644 --- a/src/test/java/org/json/junit/JSONMLTest.java +++ b/src/test/java/org/json/junit/JSONMLTest.java @@ -1052,4 +1052,61 @@ public void testValidXMLToJSONObjectStillWorks() { } } + /** + * Tests that the childNodes attribute is reserved in object-form parsing. + */ + @Test + public void testToJSONObjectRejectsReservedChildNodesAttribute() { + String xmlStr = "

text

"; + for (boolean keepStrings : new boolean[] {false, true}) { + JSONException exception = assertThrows(JSONException.class, + () -> JSONML.toJSONObject(xmlStr, keepStrings)); + assertTrue(exception.getMessage().startsWith("Reserved attribute.")); + } + } + + /** + * Tests that the ordinary childNode attribute is preserved in object-form parsing. + */ + @Test + public void testToJSONObjectPreservesChildNodeAttribute() { + String xmlStr = "

text

"; + for (boolean keepStrings : new boolean[] {false, true}) { + JSONObject jsonObject = JSONML.toJSONObject(xmlStr, keepStrings); + assertEquals("p", jsonObject.getString("tagName")); + assertEquals("metadata", jsonObject.getString("childNode")); + assertEquals("text", jsonObject.getJSONArray("childNodes").getString(0)); + } + } + + /** + * Tests that the tagName attribute remains reserved in object-form parsing. + */ + @Test + public void testToJSONObjectRejectsReservedTagNameAttribute() { + String xmlStr = "

text

"; + for (boolean keepStrings : new boolean[] {false, true}) { + JSONException exception = assertThrows(JSONException.class, + () -> JSONML.toJSONObject(xmlStr, keepStrings)); + assertTrue(exception.getMessage().startsWith("Reserved attribute.")); + } + } + + /** + * Tests that childNode and childNodes attributes are preserved in array-form parsing. + */ + @Test + public void testToJSONArrayPreservesChildNodeAttributes() { + String xmlStr = "

text

"; + for (boolean keepStrings : new boolean[] {false, true}) { + JSONArray jsonArray = JSONML.toJSONArray(xmlStr, keepStrings); + assertEquals(3, jsonArray.length()); + assertEquals("p", jsonArray.getString(0)); + JSONObject attributes = jsonArray.getJSONObject(1); + assertEquals("singular", attributes.getString("childNode")); + assertEquals("plural", attributes.getString("childNodes")); + assertEquals("text", jsonArray.getString(2)); + } + } + } From d38bff895780b44a42731f48e53529754763fbf8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=95=88=EC=8A=B9=ED=98=84?= Date: Thu, 1 Oct 2026 17:15:16 +0900 Subject: [PATCH 23/33] Extract childNodes constant in JSONML Replace the four repeated "childNodes" literals with a private static final constant. Address SonarQube rule java:S1192 without changing parsing behavior. --- src/main/java/org/json/JSONML.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/json/JSONML.java b/src/main/java/org/json/JSONML.java index 27fe2d509..937d7cfcf 100644 --- a/src/main/java/org/json/JSONML.java +++ b/src/main/java/org/json/JSONML.java @@ -14,6 +14,8 @@ */ public class JSONML { + private static final String CHILD_NODES = "childNodes"; + /** * Constructs a new JSONML object. * @deprecated (Utility class cannot be instantiated) @@ -205,7 +207,7 @@ private static Object parse( // attribute = value attribute = (String)token; - if (!arrayForm && ("tagName".equals(attribute) || "childNodes".equals(attribute))) { + if (!arrayForm && ("tagName".equals(attribute) || CHILD_NODES.equals(attribute))) { throw x.syntaxError("Reserved attribute."); } token = x.nextToken(); @@ -256,7 +258,7 @@ private static Object parse( } tagName = null; if (!arrayForm && newja.length() > 0) { - newjo.put("childNodes", newja); + newjo.put(CHILD_NODES, newja); } if (ja == null) { if (arrayForm) { @@ -648,7 +650,7 @@ public static String toString(JSONObject jo) throws JSONException { // Don't use the new entrySet API to maintain Android support for (final String key : jo.keySet()) { - if (!"tagName".equals(key) && !"childNodes".equals(key)) { + if (!"tagName".equals(key) && !CHILD_NODES.equals(key)) { XML.noSpace(key); value = jo.opt(key); if (value != null) { @@ -664,7 +666,7 @@ public static String toString(JSONObject jo) throws JSONException { //Emit content in body - ja = jo.optJSONArray("childNodes"); + ja = jo.optJSONArray(CHILD_NODES); if (ja == null) { sb.append('/'); sb.append('>'); From f3c83d83495f5f86c2f88a30f909e7e2dbbd974b Mon Sep 17 00:00:00 2001 From: boulea7 Date: Fri, 2 Oct 2026 18:18:04 +0800 Subject: [PATCH 24/33] Fix JSONML text double decoding with keepStrings --- src/main/java/org/json/JSONML.java | 2 +- src/test/java/org/json/junit/JSONMLTest.java | 92 ++++++++++++++++++++ 2 files changed, 93 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/json/JSONML.java b/src/main/java/org/json/JSONML.java index 6ec997061..5caf733f6 100644 --- a/src/main/java/org/json/JSONML.java +++ b/src/main/java/org/json/JSONML.java @@ -274,7 +274,7 @@ private static Object parse( if (token instanceof String) { String strToken = (String) token; if (config.isKeepStrings()) { - value = XML.unescape(strToken); + value = strToken; } else { value = XML.stringToValue(strToken); } diff --git a/src/test/java/org/json/junit/JSONMLTest.java b/src/test/java/org/json/junit/JSONMLTest.java index 93a6821d8..9c6d9bc05 100644 --- a/src/test/java/org/json/junit/JSONMLTest.java +++ b/src/test/java/org/json/junit/JSONMLTest.java @@ -724,6 +724,98 @@ public void testToJSONArray_reversibility() { assertNotEquals(revertedXml, originalXml); } + /** + * Entity-looking text is decoded once, including when strings are kept. + */ + @Test + public void shouldDecodeEntitiesOnceWhenKeepingStringsInJSONArray() { + final String[][] cases = { + {"&lt;", "<"}, + {"&amp;", "&"}, + {"&#65;", "A"}, + {"&lt;", "<"}, + {"<>&"'AB", "<>&\"'AB"} + }; + for (String[] testCase : cases) { + final String xml = "

" + testCase[0] + "

"; + final JSONArray json = JSONML.toJSONArray(xml, true); + assertEquals(xml, testCase[1], json.getJSONObject(1).get("title")); + assertEquals(xml, testCase[1], json.get(2)); + assertEquals(xml, testCase[1], JSONML.toJSONArray(xml, false).get(2)); + assertTrue(xml, json.similar(JSONML.toJSONArray(new XMLTokener(JSONML.toString(json)), + JSONMLParserConfiguration.KEEP_STRINGS))); + } + } + + /** + * Object form preserves the same decoded attribute and text values. + */ + @Test + public void shouldDecodeEntitiesOnceWhenKeepingStringsInJSONObject() { + final String xml = "

&lt;

"; + final JSONObject json = JSONML.toJSONObject(xml, + JSONMLParserConfiguration.ORIGINAL.withKeepStrings(true)); + assertEquals("<", json.get("title")); + assertEquals("<", json.getJSONArray("childNodes").get(0)); + assertEquals("<", JSONML.toJSONObject(xml).getJSONArray("childNodes").get(0)); + assertTrue(json.similar(JSONML.toJSONObject(new XMLTokener(JSONML.toString(json)), true))); + } + + /** + * Keeping strings disables type conversion without disabling entity decoding. + */ + @Test + public void shouldPreserveValueTypesWhenKeepingStrings() { + final String[] values = {"42", "true", "false", "null"}; + final String[] content = {"42", "true", "false", "null"}; + final Object[] typedValues = {Integer.valueOf(42), Boolean.TRUE, Boolean.FALSE, JSONObject.NULL}; + for (int i = 0; i < values.length; i++) { + final String xml = "

" + content[i] + "

"; + final JSONArray array = JSONML.toJSONArray(new XMLTokener(xml), true); + final JSONObject object = JSONML.toJSONObject(xml, true); + assertEquals(values[i], array.getJSONObject(1).get("value")); + assertEquals(values[i], array.get(2)); + assertEquals(values[i], object.get("value")); + assertEquals(values[i], object.getJSONArray("childNodes").get(0)); + final JSONArray typedArray = JSONML.toJSONArray(xml); + final JSONObject typedObject = JSONML.toJSONObject(xml); + assertEquals(typedValues[i], typedArray.getJSONObject(1).get("value")); + assertEquals(typedValues[i], typedArray.get(2)); + assertEquals(typedValues[i], typedObject.get("value")); + assertEquals(typedValues[i], typedObject.getJSONArray("childNodes").get(0)); + } + } + + /** + * CDATA entity syntax remains literal content. + */ + @Test + public void shouldPreserveCdataWhenKeepingStrings() { + final String content = "< A & 42 true null"; + final String xml = "

"; + assertEquals(content, JSONML.toJSONArray(xml, true).get(1)); + assertEquals(content, JSONML.toJSONObject(xml, true).getJSONArray("childNodes").get(0)); + } + + /** + * Escaped invalid character references are text, while raw references remain invalid. + */ + @Test + public void shouldPreserveEscapedInvalidCharacterReferences() { + final String[] references = {"#0", "#x110000"}; + for (String reference : references) { + final String expected = "&" + reference + ";"; + final String xml = "

&" + reference + ";

"; + assertEquals(expected, JSONML.toJSONArray(xml, true).get(1)); + assertEquals(expected, JSONML.toJSONObject(xml, true).getJSONArray("childNodes").get(0)); + assertEquals(expected, JSONML.toJSONArray(xml).get(1)); + assertEquals(expected, JSONML.toJSONObject(xml).getJSONArray("childNodes").get(0)); + final String invalidXml = "

" + expected + "

"; + assertThrows(JSONException.class, () -> JSONML.toJSONArray(invalidXml, true)); + assertThrows(JSONException.class, () -> JSONML.toJSONObject(invalidXml, true)); + } + } + /** * JSON string cannot be reverted to original xml when type guessing is used. * When we force all the values as string, the original text comes back. From 3d2f7e07ec2ac19ffff334ce87b4a308a09cba89 Mon Sep 17 00:00:00 2001 From: PHJ2000 <105151063+PHJ2000@users.noreply.github.com> Date: Mon, 5 Oct 2026 18:17:59 +0900 Subject: [PATCH 25/33] Preserve inherited properties without local entries --- src/main/java/org/json/Property.java | 2 +- .../java/org/json/junit/PropertyTest.java | 29 ++++++++++++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/json/Property.java b/src/main/java/org/json/Property.java index ba6c56967..bc5df3895 100644 --- a/src/main/java/org/json/Property.java +++ b/src/main/java/org/json/Property.java @@ -30,7 +30,7 @@ public static JSONObject toJSONObject(java.util.Properties properties) throws JS // can't use the new constructor for Android support // JSONObject jo = new JSONObject(properties == null ? 0 : properties.size()); JSONObject jo = new JSONObject(); - if (properties != null && !properties.isEmpty()) { + if (properties != null) { Enumeration enumProperties = properties.propertyNames(); while(enumProperties.hasMoreElements()) { String name = (String)enumProperties.nextElement(); diff --git a/src/test/java/org/json/junit/PropertyTest.java b/src/test/java/org/json/junit/PropertyTest.java index eee482fbf..268ec0a3f 100644 --- a/src/test/java/org/json/junit/PropertyTest.java +++ b/src/test/java/org/json/junit/PropertyTest.java @@ -17,6 +17,33 @@ */ public class PropertyTest { + @Test + public void shouldIncludeInheritedPropertiesWithoutLocalEntries() { + Properties defaults = new Properties(); + defaults.setProperty("timeout", "30"); + Properties properties = new Properties(new Properties(defaults)); + + JSONObject jsonObject = Property.toJSONObject(properties); + + assertEquals(1, jsonObject.length()); + assertEquals("30", jsonObject.getString("timeout")); + } + + @Test + public void shouldPreferLocalPropertiesOverDefaults() { + Properties defaults = new Properties(); + defaults.setProperty("timeout", "30"); + defaults.setProperty("host", "localhost"); + Properties properties = new Properties(defaults); + properties.setProperty("timeout", "60"); + + JSONObject jsonObject = Property.toJSONObject(properties); + + assertEquals(2, jsonObject.length()); + assertEquals("60", jsonObject.getString("timeout")); + assertEquals("localhost", jsonObject.getString("host")); + } + /** * JSONObject from null properties object should * result in an empty JSONObject. @@ -99,4 +126,4 @@ public void shouldHandleJSONProperty() { assertTrue("property objects should match", properties.equals(jsonProperties)); } -} \ No newline at end of file +} From 23bc68f227e561f55e5a226c9879c61638f37e95 Mon Sep 17 00:00:00 2001 From: Fahad Al-Dajani <130736979+fahadaldajani92@users.noreply.github.com> Date: Thu, 8 Oct 2026 16:55:26 +0300 Subject: [PATCH 26/33] test: cover literal tilde tokens in JSONPointer --- .../java/org/json/junit/JSONPointerTest.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/test/java/org/json/junit/JSONPointerTest.java b/src/test/java/org/json/junit/JSONPointerTest.java index 7095d45da..273e062fb 100644 --- a/src/test/java/org/json/junit/JSONPointerTest.java +++ b/src/test/java/org/json/junit/JSONPointerTest.java @@ -124,6 +124,24 @@ public void tokenListPreservesLiteralTokens() { assertEquals("tilde zero", new JSONPointer(java.util.Arrays.asList("~0")).queryFrom(object)); } + @Test + public void escapedTildeTokensSelectLiteralKeys() { + JSONObject object = new JSONObject().put("~1", "literal ~1").put("/", "slash") + .put("~0", "literal ~0").put("~", "tilde") + .put("a~1b", "literal a~1b").put("a/b", "a slash b") + .put("a~0b", "literal a~0b").put("a~b", "a tilde b"); + + assertEquals("literal ~1", object.query("/~01")); + assertEquals("literal ~1", object.query("#/~01")); + assertEquals("literal ~0", object.query("/~00")); + assertEquals("literal ~0", object.query("#/~00")); + assertEquals("literal a~1b", object.query("/a~01b")); + assertEquals("literal a~0b", object.query("/a~00b")); + assertEquals("literal ~1", JSONPointer.builder().append("~1").build().queryFrom(object)); + assertEquals("literal ~0", JSONPointer.builder().append("~0").build().queryFrom(object)); + assertEquals("literal ~1", new JSONPointer(java.util.Arrays.asList("~1")).queryFrom(object)); + } + /** * We pass backslashes as-is * From 564acf4eb11e33e449a884c99f622614e869b423 Mon Sep 17 00:00:00 2001 From: JimmyLiuJia <91264074+JimmyLiuJia@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:21:40 +0800 Subject: [PATCH 27/33] Preserve plus signs in JSONPointer URI fragments --- src/main/java/org/json/JSONPointer.java | 575 +++++------ .../java/org/json/junit/JSONPointerTest.java | 923 +++++++++--------- 2 files changed, 767 insertions(+), 731 deletions(-) diff --git a/src/main/java/org/json/JSONPointer.java b/src/main/java/org/json/JSONPointer.java index 83a0690d7..e06df2da5 100644 --- a/src/main/java/org/json/JSONPointer.java +++ b/src/main/java/org/json/JSONPointer.java @@ -1,287 +1,288 @@ -package org.json; - -import static java.lang.String.format; - -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/* -Public Domain. -*/ - -/** - * A JSON Pointer is a simple query language defined for JSON documents by - * RFC 6901. - * - * In a nutshell, JSONPointer allows the user to navigate into a JSON document - * using strings, and retrieve targeted objects, like a simple form of XPATH. - * Path segments are separated by the '/' char, which signifies the root of - * the document when it appears as the first char of the string. Array - * elements are navigated using ordinals, counting from 0. JSONPointer strings - * may be extended to any arbitrary number of segments. If the navigation - * is successful, the matched item is returned. A matched item may be a - * JSONObject, a JSONArray, or a JSON value. If the JSONPointer string building - * fails, an appropriate exception is thrown. If the navigation fails to find - * a match, a JSONPointerException is thrown. - * - * @author JSON.org - * @version 2016-05-14 - */ -public class JSONPointer { - - // used for URL encoding and decoding - private static final String ENCODING = "utf-8"; - - /** - * This class allows the user to build a JSONPointer in steps, using - * exactly one segment in each step. - */ - public static class Builder { - - /** - * Constructs a new Builder object. - */ - public Builder() { - } - - // Segments for the eventual JSONPointer string - private final List refTokens = new ArrayList(); - - /** - * Creates a {@code JSONPointer} instance using the tokens previously set using the - * {@link #append(String)} method calls. - * @return a JSONPointer object - */ - public JSONPointer build() { - return new JSONPointer(this.refTokens); - } - - /** - * Adds an arbitrary token to the list of reference tokens. It can be any non-null value. - * - * Unlike in the case of JSON string or URI fragment representation of JSON pointers, the - * argument of this method MUST NOT be escaped. If you want to query the property called - * {@code "a~b"} then you should simply pass the {@code "a~b"} string as-is, there is no - * need to escape it as {@code "a~0b"}. - * - * @param token the new token to be appended to the list - * @return {@code this} - * @throws NullPointerException if {@code token} is null - */ - public Builder append(String token) { - if (token == null) { - throw new NullPointerException("token cannot be null"); - } - this.refTokens.add(token); - return this; - } - - /** - * Adds an integer to the reference token list. Although not necessarily, mostly this token will - * denote an array index. - * - * @param arrayIndex the array index to be added to the token list - * @return {@code this} - */ - public Builder append(int arrayIndex) { - this.refTokens.add(String.valueOf(arrayIndex)); - return this; - } - } - - /** - * Static factory method for {@link Builder}. Example usage: - * - *

-     * JSONPointer pointer = JSONPointer.builder()
-     *       .append("obj")
-     *       .append("other~key").append("another/key")
-     *       .append("\"")
-     *       .append(0)
-     *       .build();
-     * 
- * - * @return a builder instance which can be used to construct a {@code JSONPointer} instance by chained - * {@link Builder#append(String)} calls. - */ - public static Builder builder() { - return new Builder(); - } - - // Segments for the JSONPointer string - private final List refTokens; - - /** - * Pre-parses and initializes a new {@code JSONPointer} instance. If you want to - * evaluate the same JSON Pointer on different JSON documents then it is recommended - * to keep the {@code JSONPointer} instances due to performance considerations. - * - * @param pointer the JSON String or URI Fragment representation of the JSON pointer. - * @throws IllegalArgumentException if {@code pointer} is not a valid JSON pointer - */ - public JSONPointer(final String pointer) { - if (pointer == null) { - throw new NullPointerException("pointer cannot be null"); - } - if (pointer.isEmpty() || "#".equals(pointer)) { - this.refTokens = Collections.emptyList(); - return; - } - String refs; - if (pointer.startsWith("#/")) { - refs = pointer.substring(2); - try { - refs = URLDecoder.decode(refs, ENCODING); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - } else if (pointer.startsWith("/")) { - refs = pointer.substring(1); - } else { - throw new IllegalArgumentException("a JSON pointer should start with '/' or '#/'"); - } - this.refTokens = new ArrayList(); - int slashIdx = -1; - int prevSlashIdx = 0; - do { - prevSlashIdx = slashIdx + 1; - slashIdx = refs.indexOf('/', prevSlashIdx); - if(prevSlashIdx == slashIdx || prevSlashIdx == refs.length()) { - // found 2 slashes in a row ( obj//next ) - // or single slash at the end of a string ( obj/test/ ) - this.refTokens.add(""); - } else if (slashIdx >= 0) { - final String token = refs.substring(prevSlashIdx, slashIdx); - this.refTokens.add(unescape(token)); - } else { - // last item after separator, or no separator at all. - final String token = refs.substring(prevSlashIdx); - this.refTokens.add(unescape(token)); - } - } while (slashIdx >= 0); - // using split does not take into account consecutive separators or "ending nulls" - //for (String token : refs.split("/")) { - // this.refTokens.add(unescape(token)); - //} - } - - /** - * Constructs a new JSONPointer instance with the provided list of reference tokens. - * - * @param refTokens A list of strings representing the reference tokens for the JSON Pointer. - * Each token identifies a step in the path to the targeted value. - */ - public JSONPointer(List refTokens) { - this.refTokens = new ArrayList(refTokens); - } - - /** - * @see rfc6901 section 3 - */ - private static String unescape(String token) { - return token.replace("~1", "/").replace("~0", "~"); - } - - /** - * Evaluates this JSON Pointer on the given {@code document}. The {@code document} - * is usually a {@link JSONObject} or a {@link JSONArray} instance, but the empty - * JSON Pointer ({@code ""}) can be evaluated on any JSON values and in such case the - * returned value will be {@code document} itself. - * - * @param document the JSON document which should be the subject of querying. - * @return the result of the evaluation - * @throws JSONPointerException if an error occurs during evaluation - */ - public Object queryFrom(Object document) throws JSONPointerException { - if (this.refTokens.isEmpty()) { - return document; - } - Object current = document; - for (String token : this.refTokens) { - if (current instanceof JSONObject) { - current = ((JSONObject) current).opt(token); - } else if (current instanceof JSONArray) { - current = readByIndexToken(current, token); - } else { - throw new JSONPointerException(format( - "value [%s] is not an array or object therefore its key %s cannot be resolved", current, - token)); - } - } - return current; - } - - /** - * Matches a JSONArray element by ordinal position - * @param current the JSONArray to be evaluated - * @param indexToken the array index in string form - * @return the matched object. If no matching item is found a - * @throws JSONPointerException is thrown if the index is out of bounds - */ - private static Object readByIndexToken(Object current, String indexToken) throws JSONPointerException { - try { - int index = Integer.parseInt(indexToken); - JSONArray currentArr = (JSONArray) current; - if (index >= currentArr.length()) { - throw new JSONPointerException(format("index %s is out of bounds - the array has %d elements", indexToken, - Integer.valueOf(currentArr.length()))); - } - try { - return currentArr.get(index); - } catch (JSONException e) { - throw new JSONPointerException("Error reading value at index position " + index, e); - } - } catch (NumberFormatException e) { - throw new JSONPointerException(format("%s is not an array index", indexToken), e); - } - } - - /** - * Returns a string representing the JSONPointer path value using string - * representation - */ - @Override - public String toString() { - StringBuilder rval = new StringBuilder(); - for (String token: this.refTokens) { - rval.append('/').append(escape(token)); - } - return rval.toString(); - } - - /** - * Escapes path segment values to an unambiguous form. - * The escape char to be inserted is '~'. The chars to be escaped - * are ~, which maps to ~0, and /, which maps to ~1. - * @param token the JSONPointer segment value to be escaped - * @return the escaped value for the token - * - * @see rfc6901 section 3 - */ - private static String escape(String token) { - return token.replace("~", "~0") - .replace("/", "~1"); - } - - /** - * Returns a string representing the JSONPointer path value using URI - * fragment identifier representation - * @return a uri fragment string - */ - public String toURIFragment() { - try { - StringBuilder rval = new StringBuilder("#"); - for (String token : this.refTokens) { - rval.append('/').append(URLEncoder.encode(escape(token), ENCODING)); - } - return rval.toString(); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - } - -} +package org.json; + +import static java.lang.String.format; + +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/* +Public Domain. +*/ + +/** + * A JSON Pointer is a simple query language defined for JSON documents by + * RFC 6901. + * + * In a nutshell, JSONPointer allows the user to navigate into a JSON document + * using strings, and retrieve targeted objects, like a simple form of XPATH. + * Path segments are separated by the '/' char, which signifies the root of + * the document when it appears as the first char of the string. Array + * elements are navigated using ordinals, counting from 0. JSONPointer strings + * may be extended to any arbitrary number of segments. If the navigation + * is successful, the matched item is returned. A matched item may be a + * JSONObject, a JSONArray, or a JSON value. If the JSONPointer string building + * fails, an appropriate exception is thrown. If the navigation fails to find + * a match, a JSONPointerException is thrown. + * + * @author JSON.org + * @version 2016-05-14 + */ +public class JSONPointer { + + // used for URL encoding and decoding + private static final String ENCODING = "utf-8"; + + /** + * This class allows the user to build a JSONPointer in steps, using + * exactly one segment in each step. + */ + public static class Builder { + + /** + * Constructs a new Builder object. + */ + public Builder() { + } + + // Segments for the eventual JSONPointer string + private final List refTokens = new ArrayList(); + + /** + * Creates a {@code JSONPointer} instance using the tokens previously set using the + * {@link #append(String)} method calls. + * @return a JSONPointer object + */ + public JSONPointer build() { + return new JSONPointer(this.refTokens); + } + + /** + * Adds an arbitrary token to the list of reference tokens. It can be any non-null value. + * + * Unlike in the case of JSON string or URI fragment representation of JSON pointers, the + * argument of this method MUST NOT be escaped. If you want to query the property called + * {@code "a~b"} then you should simply pass the {@code "a~b"} string as-is, there is no + * need to escape it as {@code "a~0b"}. + * + * @param token the new token to be appended to the list + * @return {@code this} + * @throws NullPointerException if {@code token} is null + */ + public Builder append(String token) { + if (token == null) { + throw new NullPointerException("token cannot be null"); + } + this.refTokens.add(token); + return this; + } + + /** + * Adds an integer to the reference token list. Although not necessarily, mostly this token will + * denote an array index. + * + * @param arrayIndex the array index to be added to the token list + * @return {@code this} + */ + public Builder append(int arrayIndex) { + this.refTokens.add(String.valueOf(arrayIndex)); + return this; + } + } + + /** + * Static factory method for {@link Builder}. Example usage: + * + *

+     * JSONPointer pointer = JSONPointer.builder()
+     *       .append("obj")
+     *       .append("other~key").append("another/key")
+     *       .append("\"")
+     *       .append(0)
+     *       .build();
+     * 
+ * + * @return a builder instance which can be used to construct a {@code JSONPointer} instance by chained + * {@link Builder#append(String)} calls. + */ + public static Builder builder() { + return new Builder(); + } + + // Segments for the JSONPointer string + private final List refTokens; + + /** + * Pre-parses and initializes a new {@code JSONPointer} instance. If you want to + * evaluate the same JSON Pointer on different JSON documents then it is recommended + * to keep the {@code JSONPointer} instances due to performance considerations. + * + * @param pointer the JSON String or URI Fragment representation of the JSON pointer. + * @throws IllegalArgumentException if {@code pointer} is not a valid JSON pointer + */ + public JSONPointer(final String pointer) { + if (pointer == null) { + throw new NullPointerException("pointer cannot be null"); + } + if (pointer.isEmpty() || "#".equals(pointer)) { + this.refTokens = Collections.emptyList(); + return; + } + String refs; + if (pointer.startsWith("#/")) { + refs = pointer.substring(2); + try { + // URI fragments preserve plus signs rather than treating them as form-encoded spaces. + refs = URLDecoder.decode(refs.replace("+", "%2B"), ENCODING); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } else if (pointer.startsWith("/")) { + refs = pointer.substring(1); + } else { + throw new IllegalArgumentException("a JSON pointer should start with '/' or '#/'"); + } + this.refTokens = new ArrayList(); + int slashIdx = -1; + int prevSlashIdx = 0; + do { + prevSlashIdx = slashIdx + 1; + slashIdx = refs.indexOf('/', prevSlashIdx); + if(prevSlashIdx == slashIdx || prevSlashIdx == refs.length()) { + // found 2 slashes in a row ( obj//next ) + // or single slash at the end of a string ( obj/test/ ) + this.refTokens.add(""); + } else if (slashIdx >= 0) { + final String token = refs.substring(prevSlashIdx, slashIdx); + this.refTokens.add(unescape(token)); + } else { + // last item after separator, or no separator at all. + final String token = refs.substring(prevSlashIdx); + this.refTokens.add(unescape(token)); + } + } while (slashIdx >= 0); + // using split does not take into account consecutive separators or "ending nulls" + //for (String token : refs.split("/")) { + // this.refTokens.add(unescape(token)); + //} + } + + /** + * Constructs a new JSONPointer instance with the provided list of reference tokens. + * + * @param refTokens A list of strings representing the reference tokens for the JSON Pointer. + * Each token identifies a step in the path to the targeted value. + */ + public JSONPointer(List refTokens) { + this.refTokens = new ArrayList(refTokens); + } + + /** + * @see rfc6901 section 3 + */ + private static String unescape(String token) { + return token.replace("~1", "/").replace("~0", "~"); + } + + /** + * Evaluates this JSON Pointer on the given {@code document}. The {@code document} + * is usually a {@link JSONObject} or a {@link JSONArray} instance, but the empty + * JSON Pointer ({@code ""}) can be evaluated on any JSON values and in such case the + * returned value will be {@code document} itself. + * + * @param document the JSON document which should be the subject of querying. + * @return the result of the evaluation + * @throws JSONPointerException if an error occurs during evaluation + */ + public Object queryFrom(Object document) throws JSONPointerException { + if (this.refTokens.isEmpty()) { + return document; + } + Object current = document; + for (String token : this.refTokens) { + if (current instanceof JSONObject) { + current = ((JSONObject) current).opt(token); + } else if (current instanceof JSONArray) { + current = readByIndexToken(current, token); + } else { + throw new JSONPointerException(format( + "value [%s] is not an array or object therefore its key %s cannot be resolved", current, + token)); + } + } + return current; + } + + /** + * Matches a JSONArray element by ordinal position + * @param current the JSONArray to be evaluated + * @param indexToken the array index in string form + * @return the matched object. If no matching item is found a + * @throws JSONPointerException is thrown if the index is out of bounds + */ + private static Object readByIndexToken(Object current, String indexToken) throws JSONPointerException { + try { + int index = Integer.parseInt(indexToken); + JSONArray currentArr = (JSONArray) current; + if (index >= currentArr.length()) { + throw new JSONPointerException(format("index %s is out of bounds - the array has %d elements", indexToken, + Integer.valueOf(currentArr.length()))); + } + try { + return currentArr.get(index); + } catch (JSONException e) { + throw new JSONPointerException("Error reading value at index position " + index, e); + } + } catch (NumberFormatException e) { + throw new JSONPointerException(format("%s is not an array index", indexToken), e); + } + } + + /** + * Returns a string representing the JSONPointer path value using string + * representation + */ + @Override + public String toString() { + StringBuilder rval = new StringBuilder(); + for (String token: this.refTokens) { + rval.append('/').append(escape(token)); + } + return rval.toString(); + } + + /** + * Escapes path segment values to an unambiguous form. + * The escape char to be inserted is '~'. The chars to be escaped + * are ~, which maps to ~0, and /, which maps to ~1. + * @param token the JSONPointer segment value to be escaped + * @return the escaped value for the token + * + * @see rfc6901 section 3 + */ + private static String escape(String token) { + return token.replace("~", "~0") + .replace("/", "~1"); + } + + /** + * Returns a string representing the JSONPointer path value using URI + * fragment identifier representation + * @return a uri fragment string + */ + public String toURIFragment() { + try { + StringBuilder rval = new StringBuilder("#"); + for (String token : this.refTokens) { + rval.append('/').append(URLEncoder.encode(escape(token), ENCODING).replace("+", "%20")); + } + return rval.toString(); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/src/test/java/org/json/junit/JSONPointerTest.java b/src/test/java/org/json/junit/JSONPointerTest.java index 7095d45da..9275efab0 100644 --- a/src/test/java/org/json/junit/JSONPointerTest.java +++ b/src/test/java/org/json/junit/JSONPointerTest.java @@ -1,444 +1,479 @@ -package org.json.junit; - -/* -Public Domain. -*/ - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.InputStream; - -import org.json.JSONArray; -import org.json.JSONObject; -import org.json.JSONPointer; -import org.json.JSONPointerException; -import org.json.JSONTokener; -import org.junit.Test; - -public class JSONPointerTest { - - private static final JSONObject document; - private static final String EXPECTED_COMPLETE_DOCUMENT = "{\"\":0,\" \":7,\"g|h\":4,\"c%d\":2,\"k\\\"l\":6,\"a/b\":1,\"i\\\\j\":5," + - "\"obj\":{\"\":{\"\":\"empty key of an object with an empty key\",\"subKey\":\"Some other value\"}," + - "\"other~key\":{\"another/key\":[\"val\"]},\"key\":\"value\"},\"foo\":[\"bar\",\"baz\"],\"e^f\":3," + - "\"m~n\":8}"; - - - static { - @SuppressWarnings("resource") - InputStream resourceAsStream = JSONPointerTest.class.getClassLoader().getResourceAsStream("jsonpointer-testdoc.json"); - if(resourceAsStream == null) { - throw new ExceptionInInitializerError("Unable to locate test file. Please check your development environment configuration"); - } - document = new JSONObject(new JSONTokener(resourceAsStream)); - } - - private Object query(String pointer) { - return new JSONPointer(pointer).queryFrom(document); - } - - @Test - public void emptyPointer() { - assertTrue(new JSONObject(EXPECTED_COMPLETE_DOCUMENT).similar(query(""))); - } - - @SuppressWarnings("unused") - @Test(expected = NullPointerException.class) - public void nullPointer() { - new JSONPointer((String) null); - } - - @Test - public void objectPropertyQuery() { - assertEquals("[\"bar\",\"baz\"]", query("/foo").toString()); - } - - @Test - public void arrayIndexQuery() { - assertEquals("bar", query("/foo/0")); - } - - @Test(expected = JSONPointerException.class) - public void stringPropOfArrayFailure() { - query("/foo/bar"); - } - - @Test - public void queryByEmptyKey() { - assertEquals(0, query("/")); - } - - @Test - public void queryByEmptyKeySubObject() { - JSONObject json = new JSONObject("{\"\":\"empty key of an object with an empty key\",\"subKey\":\"Some" + - " other value\"}"); - JSONObject obj = (JSONObject) query("/obj/"); - assertTrue(json.similar(obj)); - } - - @Test - public void queryByEmptyKeySubObjectSubOject() { - assertEquals("empty key of an object with an empty key", query("/obj//")); - } - - @Test - public void queryByEmptyKeySubObjectValue() { - assertEquals("Some other value", query("/obj//subKey")); - } - - @Test - public void slashEscaping() { - assertEquals(1, query("/a~1b")); - } - - @Test - public void tildeEscaping() { - assertEquals(8, query("/m~0n")); - } - - @Test - public void escapeSequencesInObjectKeys() { - JSONObject object = new JSONObject().put("~1", "tilde one").put("/", "slash") - .put("~0", "tilde zero").put("~", "tilde"); - assertEquals("tilde one", object.query("/~01")); - assertEquals("tilde zero", object.query("/~00")); - assertEquals("tilde one", object.query("#/~01")); - assertEquals("tilde zero", object.query("#/~00")); - } - - @Test - public void builderPreservesLiteralTokens() { - JSONObject object = new JSONObject().put("~1", "tilde one").put("/", "slash") - .put("~0", "tilde zero").put("~", "tilde"); - assertEquals("tilde one", JSONPointer.builder().append("~1").build().queryFrom(object)); - assertEquals("tilde zero", JSONPointer.builder().append("~0").build().queryFrom(object)); - } - - @Test - public void tokenListPreservesLiteralTokens() { - JSONObject object = new JSONObject().put("~1", "tilde one").put("/", "slash") - .put("~0", "tilde zero").put("~", "tilde"); - assertEquals("tilde one", new JSONPointer(java.util.Arrays.asList("~1")).queryFrom(object)); - assertEquals("tilde zero", new JSONPointer(java.util.Arrays.asList("~0")).queryFrom(object)); - } - - /** - * We pass backslashes as-is - * - * @see rfc6901 section 3 - */ - @Test - public void backslashHandling() { - assertEquals(5, query("/i\\j")); - } - - /** - * We pass quotations as-is - * - * @see rfc6901 section 3 - */ - @Test - public void quotationHandling() { - assertEquals(6, query("/k\"l")); - } - - @Test - public void whitespaceKey() { - assertEquals(7, query("/ ")); - } - - @Test - public void uriFragmentNotation() { - assertEquals("[\"bar\",\"baz\"]", query("#/foo").toString()); - } - - @Test - public void uriFragmentNotationRoot() { - assertTrue(new JSONObject(EXPECTED_COMPLETE_DOCUMENT).similar(query("#"))); - } - - @Test - public void uriFragmentPercentHandling() { - assertEquals(2, query("#/c%25d")); - assertEquals(3, query("#/e%5Ef")); - assertEquals(4, query("#/g%7Ch")); - assertEquals(8, query("#/m~0n")); - } - - @SuppressWarnings("unused") - @Test(expected = IllegalArgumentException.class) - public void syntaxError() { - new JSONPointer("key"); - } - - @Test(expected = JSONPointerException.class) - public void arrayIndexFailure() { - query("/foo/2"); - } - - @Test(expected = JSONPointerException.class) - public void primitiveFailure() { - query("/obj/key/failure"); - } - - @Test - public void builderTest() { - JSONPointer pointer = JSONPointer.builder() - .append("obj") - .append("other~key").append("another/key") - .append(0) - .build(); - assertEquals("val", pointer.queryFrom(document)); - } - - @Test(expected = NullPointerException.class) - public void nullToken() { - JSONPointer.builder().append(null); - } - - @Test - public void toStringEscaping() { - JSONPointer pointer = JSONPointer.builder() - .append("obj") - .append("other~key").append("another/key") - .append("\"") - .append(0) - .build(); - assertEquals("/obj/other~0key/another~1key/\"/0", pointer.toString()); - } - - @Test - public void emptyPointerToString() { - assertEquals("", new JSONPointer("").toString()); - } - - @Test - public void toURIFragment() { - assertEquals("#/c%25d", new JSONPointer("/c%d").toURIFragment()); - assertEquals("#/e%5Ef", new JSONPointer("/e^f").toURIFragment()); - assertEquals("#/g%7Ch", new JSONPointer("/g|h").toURIFragment()); - assertEquals("#/m%7E0n", new JSONPointer("/m~n").toURIFragment()); - } - - @Test - public void toURIFragmentEscaping() { - JSONPointer pointer = JSONPointer.builder() - .append("obj") - .append("other~key").append("another/key") - .append(0) - .build(); - assertEquals("#/obj/other%7E0key/another%7E1key/0", pointer.toURIFragment()); - assertEquals("val", new JSONPointer(pointer.toURIFragment()).queryFrom(document)); - } - - @Test - public void toURIFragmentRoundTrip() { - JSONObject object = new JSONObject().put("~1", "tilde one").put("/", "slash"); - JSONPointer tildeOne = JSONPointer.builder().append("~1").build(); - JSONPointer slash = JSONPointer.builder().append("/").build(); - assertEquals("tilde one", object.query(tildeOne.toURIFragment())); - assertEquals("slash", object.query(slash.toURIFragment())); - } - - @Test - public void tokenListIsCopiedInConstructor() { - JSONPointer.Builder b = JSONPointer.builder().append("key1"); - JSONPointer jp1 = b.build(); - b.append("key2"); - JSONPointer jp2 = b.build(); - if(jp1.toString().equals(jp2.toString())) { - fail("Oops, my pointers are sharing a backing array"); - } - } - - /** - * Coverage for JSONObject query(String) - */ - @Test - public void queryFromJSONObject() { - String str = "{"+ - "\"stringKey\":\"hello world!\","+ - "\"arrayKey\":[0,1,2],"+ - "\"objectKey\": {"+ - "\"a\":\"aVal\","+ - "\"b\":\"bVal\""+ - "}"+ - "}"; - JSONObject jsonObject = new JSONObject(str); - Object obj = jsonObject.query("/stringKey"); - assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); - obj = jsonObject.query("/arrayKey/1"); - assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); - obj = jsonObject.query("/objectKey/b"); - assertTrue("Expected bVal", "bVal".equals(obj)); - try { - obj = jsonObject.query("/a/b/c"); - assertTrue("Expected JSONPointerException", false); - } catch (JSONPointerException e) { - assertTrue("Expected bad key/value exception", - "value [null] is not an array or object therefore its key b cannot be resolved". - equals(e.getMessage())); - } - } - - /** - * Coverage for JSONObject query(JSONPointer) - */ - @Test - public void queryFromJSONObjectUsingPointer() { - String str = "{"+ - "\"stringKey\":\"hello world!\","+ - "\"arrayKey\":[0,1,2],"+ - "\"objectKey\": {"+ - "\"a\":\"aVal\","+ - "\"b\":\"bVal\""+ - "}"+ - "}"; - JSONObject jsonObject = new JSONObject(str); - Object obj = jsonObject.query(new JSONPointer("/stringKey")); - assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); - obj = jsonObject.query(new JSONPointer("/arrayKey/1")); - assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); - obj = jsonObject.query(new JSONPointer("/objectKey/b")); - assertTrue("Expected bVal", "bVal".equals(obj)); - try { - obj = jsonObject.query(new JSONPointer("/a/b/c")); - assertTrue("Expected JSONPointerException", false); - } catch (JSONPointerException e) { - assertTrue("Expected bad key/value exception", - "value [null] is not an array or object therefore its key b cannot be resolved". - equals(e.getMessage())); - } - } - - /** - * Coverage for JSONObject optQuery(JSONPointer) - */ - @Test - public void optQueryFromJSONObjectUsingPointer() { - String str = "{"+ - "\"stringKey\":\"hello world!\","+ - "\"arrayKey\":[0,1,2],"+ - "\"objectKey\": {"+ - "\"a\":\"aVal\","+ - "\"b\":\"bVal\""+ - "}"+ - "}"; - JSONObject jsonObject = new JSONObject(str); - Object obj = jsonObject.optQuery(new JSONPointer("/stringKey")); - assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); - obj = jsonObject.optQuery(new JSONPointer("/arrayKey/1")); - assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); - obj = jsonObject.optQuery(new JSONPointer("/objectKey/b")); - assertTrue("Expected bVal", "bVal".equals(obj)); - obj = jsonObject.optQuery(new JSONPointer("/a/b/c")); - assertTrue("Expected null", obj == null); - } - - /** - * Coverage for JSONArray query(String) - */ - @Test - public void queryFromJSONArray() { - String str = "["+ - "\"hello world!\","+ - "[0,1,2],"+ - "{"+ - "\"a\":\"aVal\","+ - "\"b\":\"bVal\""+ - "}"+ - "]"; - JSONArray jsonArray = new JSONArray(str); - Object obj = jsonArray.query("/0"); - assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); - obj = jsonArray.query("/1/1"); - assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); - obj = jsonArray.query("/2/b"); - assertTrue("Expected bVal", "bVal".equals(obj)); - try { - obj = jsonArray.query("/a/b/c"); - assertTrue("Expected JSONPointerException", false); - } catch (JSONPointerException e) { - assertTrue("Expected bad index exception", - "a is not an array index".equals(e.getMessage())); - } - } - - /** - * Coverage for JSONArray query(JSONPointer) - */ - @Test - public void queryFromJSONArrayUsingPointer() { - String str = "["+ - "\"hello world!\","+ - "[0,1,2],"+ - "{"+ - "\"a\":\"aVal\","+ - "\"b\":\"bVal\""+ - "}"+ - "]"; - JSONArray jsonArray = new JSONArray(str); - Object obj = jsonArray.query(new JSONPointer("/0")); - assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); - obj = jsonArray.query(new JSONPointer("/1/1")); - assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); - obj = jsonArray.query(new JSONPointer("/2/b")); - assertTrue("Expected bVal", "bVal".equals(obj)); - try { - obj = jsonArray.query(new JSONPointer("/a/b/c")); - assertTrue("Expected JSONPointerException", false); - } catch (JSONPointerException e) { - assertTrue("Expected bad index exception", - "a is not an array index".equals(e.getMessage())); - } - } - - /** - * Coverage for JSONArray optQuery(JSONPointer) - */ - @Test - public void optQueryFromJSONArrayUsingPointer() { - String str = "["+ - "\"hello world!\","+ - "[0,1,2],"+ - "{"+ - "\"a\":\"aVal\","+ - "\"b\":\"bVal\""+ - "}"+ - "]"; - JSONArray jsonArray = new JSONArray(str); - Object obj = jsonArray.optQuery(new JSONPointer("/0")); - assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); - obj = jsonArray.optQuery(new JSONPointer("/1/1")); - assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); - obj = jsonArray.optQuery(new JSONPointer("/2/b")); - assertTrue("Expected bVal", "bVal".equals(obj)); - obj = jsonArray.optQuery(new JSONPointer("/a/b/c")); - assertTrue("Expected null", obj == null); - } - - /** - * When creating a jsonObject we need to parse escaped characters "\\\\" - * --> it's the string representation of "\\", so when query'ing via the JSONPointer - * we DON'T escape them - * - */ - @Test - public void queryFromJSONObjectUsingPointer0() { - String str = "{"+ - "\"string\\\\\\\\Key\":\"hello world!\","+ - - "\"\\\\\":\"slash test\"" + - "}"; - JSONObject jsonObject = new JSONObject(str); - //Summary of issue: When a KEY in the jsonObject is "\\\\" --> it's held - // as "\\" which means when querying, we need to use "\\" - Object twoBackslahObj = jsonObject.optQuery(new JSONPointer("/\\")); - assertEquals("slash test", twoBackslahObj); - - Object fourBackslashObj = jsonObject.optQuery(new JSONPointer("/string\\\\Key")); - assertEquals("hello world!", fourBackslashObj); - } -} +package org.json.junit; + +/* +Public Domain. +*/ + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.InputStream; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.json.JSONPointer; +import org.json.JSONPointerException; +import org.json.JSONTokener; +import org.junit.Test; + +public class JSONPointerTest { + + private static final JSONObject document; + private static final String EXPECTED_COMPLETE_DOCUMENT = "{\"\":0,\" \":7,\"g|h\":4,\"c%d\":2,\"k\\\"l\":6,\"a/b\":1,\"i\\\\j\":5," + + "\"obj\":{\"\":{\"\":\"empty key of an object with an empty key\",\"subKey\":\"Some other value\"}," + + "\"other~key\":{\"another/key\":[\"val\"]},\"key\":\"value\"},\"foo\":[\"bar\",\"baz\"],\"e^f\":3," + + "\"m~n\":8}"; + + + static { + @SuppressWarnings("resource") + InputStream resourceAsStream = JSONPointerTest.class.getClassLoader().getResourceAsStream("jsonpointer-testdoc.json"); + if(resourceAsStream == null) { + throw new ExceptionInInitializerError("Unable to locate test file. Please check your development environment configuration"); + } + document = new JSONObject(new JSONTokener(resourceAsStream)); + } + + private Object query(String pointer) { + return new JSONPointer(pointer).queryFrom(document); + } + + @Test + public void emptyPointer() { + assertTrue(new JSONObject(EXPECTED_COMPLETE_DOCUMENT).similar(query(""))); + } + + @SuppressWarnings("unused") + @Test(expected = NullPointerException.class) + public void nullPointer() { + new JSONPointer((String) null); + } + + @Test + public void objectPropertyQuery() { + assertEquals("[\"bar\",\"baz\"]", query("/foo").toString()); + } + + @Test + public void arrayIndexQuery() { + assertEquals("bar", query("/foo/0")); + } + + @Test(expected = JSONPointerException.class) + public void stringPropOfArrayFailure() { + query("/foo/bar"); + } + + @Test + public void queryByEmptyKey() { + assertEquals(0, query("/")); + } + + @Test + public void queryByEmptyKeySubObject() { + JSONObject json = new JSONObject("{\"\":\"empty key of an object with an empty key\",\"subKey\":\"Some" + + " other value\"}"); + JSONObject obj = (JSONObject) query("/obj/"); + assertTrue(json.similar(obj)); + } + + @Test + public void queryByEmptyKeySubObjectSubOject() { + assertEquals("empty key of an object with an empty key", query("/obj//")); + } + + @Test + public void queryByEmptyKeySubObjectValue() { + assertEquals("Some other value", query("/obj//subKey")); + } + + @Test + public void slashEscaping() { + assertEquals(1, query("/a~1b")); + } + + @Test + public void tildeEscaping() { + assertEquals(8, query("/m~0n")); + } + + @Test + public void escapeSequencesInObjectKeys() { + JSONObject object = new JSONObject().put("~1", "tilde one").put("/", "slash") + .put("~0", "tilde zero").put("~", "tilde"); + assertEquals("tilde one", object.query("/~01")); + assertEquals("tilde zero", object.query("/~00")); + assertEquals("tilde one", object.query("#/~01")); + assertEquals("tilde zero", object.query("#/~00")); + } + + @Test + public void builderPreservesLiteralTokens() { + JSONObject object = new JSONObject().put("~1", "tilde one").put("/", "slash") + .put("~0", "tilde zero").put("~", "tilde"); + assertEquals("tilde one", JSONPointer.builder().append("~1").build().queryFrom(object)); + assertEquals("tilde zero", JSONPointer.builder().append("~0").build().queryFrom(object)); + } + + @Test + public void tokenListPreservesLiteralTokens() { + JSONObject object = new JSONObject().put("~1", "tilde one").put("/", "slash") + .put("~0", "tilde zero").put("~", "tilde"); + assertEquals("tilde one", new JSONPointer(java.util.Arrays.asList("~1")).queryFrom(object)); + assertEquals("tilde zero", new JSONPointer(java.util.Arrays.asList("~0")).queryFrom(object)); + } + + /** + * We pass backslashes as-is + * + * @see rfc6901 section 3 + */ + @Test + public void backslashHandling() { + assertEquals(5, query("/i\\j")); + } + + /** + * We pass quotations as-is + * + * @see rfc6901 section 3 + */ + @Test + public void quotationHandling() { + assertEquals(6, query("/k\"l")); + } + + @Test + public void whitespaceKey() { + assertEquals(7, query("/ ")); + } + + @Test + public void uriFragmentNotation() { + assertEquals("[\"bar\",\"baz\"]", query("#/foo").toString()); + } + + @Test + public void uriFragmentNotationRoot() { + assertTrue(new JSONObject(EXPECTED_COMPLETE_DOCUMENT).similar(query("#"))); + } + + @Test + public void uriFragmentPercentHandling() { + assertEquals(2, query("#/c%25d")); + assertEquals(3, query("#/e%5Ef")); + assertEquals(4, query("#/g%7Ch")); + assertEquals(8, query("#/m~0n")); + } + + @Test + public void uriFragmentPreservesLiteralPlus() { + JSONObject object = new JSONObject().put("a+b", "plus").put("a b", "space") + .put("a%2Bb", "percent"); + assertEquals("plus", object.query("#/a+b")); + assertEquals("plus", object.query("#/a%2Bb")); + assertEquals("space", object.query("#/a%20b")); + assertEquals("percent", object.query("#/a%252Bb")); + assertEquals("plus", object.query("/a+b")); + } + + @Test + public void uriFragmentEncodesSpaces() { + JSONObject object = new JSONObject().put("a+b", "plus").put("a b", "space"); + JSONPointer plus = JSONPointer.builder().append("a+b").build(); + JSONPointer space = JSONPointer.builder().append("a b").build(); + assertEquals("#/a%2Bb", plus.toURIFragment()); + assertEquals("#/a%20b", space.toURIFragment()); + assertEquals("#/%20", new JSONPointer("/ ").toURIFragment()); + assertEquals("plus", object.query(plus.toURIFragment())); + assertEquals("space", object.query(space.toURIFragment())); + } + + @Test + public void uriFragmentPreservesUtf8AndPointerEscapes() { + String key = "\u4e2d +/~1"; + JSONObject object = new JSONObject().put(key, "expected") + .put("\u4e2d /~1", "wrong space"); + assertEquals("expected", object.query("#/%E4%B8%AD%20+~1~01")); + assertEquals("expected", object.query("#/%E4%B8%AD%20%2B%7E1%7E01")); + JSONPointer pointer = JSONPointer.builder().append(key).build(); + assertEquals("#/%E4%B8%AD%20%2B%7E1%7E01", pointer.toURIFragment()); + assertEquals("expected", object.query(pointer.toURIFragment())); + } + + @SuppressWarnings("unused") + @Test(expected = IllegalArgumentException.class) + public void syntaxError() { + new JSONPointer("key"); + } + + @Test(expected = JSONPointerException.class) + public void arrayIndexFailure() { + query("/foo/2"); + } + + @Test(expected = JSONPointerException.class) + public void primitiveFailure() { + query("/obj/key/failure"); + } + + @Test + public void builderTest() { + JSONPointer pointer = JSONPointer.builder() + .append("obj") + .append("other~key").append("another/key") + .append(0) + .build(); + assertEquals("val", pointer.queryFrom(document)); + } + + @Test(expected = NullPointerException.class) + public void nullToken() { + JSONPointer.builder().append(null); + } + + @Test + public void toStringEscaping() { + JSONPointer pointer = JSONPointer.builder() + .append("obj") + .append("other~key").append("another/key") + .append("\"") + .append(0) + .build(); + assertEquals("/obj/other~0key/another~1key/\"/0", pointer.toString()); + } + + @Test + public void emptyPointerToString() { + assertEquals("", new JSONPointer("").toString()); + } + + @Test + public void toURIFragment() { + assertEquals("#/c%25d", new JSONPointer("/c%d").toURIFragment()); + assertEquals("#/e%5Ef", new JSONPointer("/e^f").toURIFragment()); + assertEquals("#/g%7Ch", new JSONPointer("/g|h").toURIFragment()); + assertEquals("#/m%7E0n", new JSONPointer("/m~n").toURIFragment()); + } + + @Test + public void toURIFragmentEscaping() { + JSONPointer pointer = JSONPointer.builder() + .append("obj") + .append("other~key").append("another/key") + .append(0) + .build(); + assertEquals("#/obj/other%7E0key/another%7E1key/0", pointer.toURIFragment()); + assertEquals("val", new JSONPointer(pointer.toURIFragment()).queryFrom(document)); + } + + @Test + public void toURIFragmentRoundTrip() { + JSONObject object = new JSONObject().put("~1", "tilde one").put("/", "slash"); + JSONPointer tildeOne = JSONPointer.builder().append("~1").build(); + JSONPointer slash = JSONPointer.builder().append("/").build(); + assertEquals("tilde one", object.query(tildeOne.toURIFragment())); + assertEquals("slash", object.query(slash.toURIFragment())); + } + + @Test + public void tokenListIsCopiedInConstructor() { + JSONPointer.Builder b = JSONPointer.builder().append("key1"); + JSONPointer jp1 = b.build(); + b.append("key2"); + JSONPointer jp2 = b.build(); + if(jp1.toString().equals(jp2.toString())) { + fail("Oops, my pointers are sharing a backing array"); + } + } + + /** + * Coverage for JSONObject query(String) + */ + @Test + public void queryFromJSONObject() { + String str = "{"+ + "\"stringKey\":\"hello world!\","+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\": {"+ + "\"a\":\"aVal\","+ + "\"b\":\"bVal\""+ + "}"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + Object obj = jsonObject.query("/stringKey"); + assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); + obj = jsonObject.query("/arrayKey/1"); + assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); + obj = jsonObject.query("/objectKey/b"); + assertTrue("Expected bVal", "bVal".equals(obj)); + try { + obj = jsonObject.query("/a/b/c"); + assertTrue("Expected JSONPointerException", false); + } catch (JSONPointerException e) { + assertTrue("Expected bad key/value exception", + "value [null] is not an array or object therefore its key b cannot be resolved". + equals(e.getMessage())); + } + } + + /** + * Coverage for JSONObject query(JSONPointer) + */ + @Test + public void queryFromJSONObjectUsingPointer() { + String str = "{"+ + "\"stringKey\":\"hello world!\","+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\": {"+ + "\"a\":\"aVal\","+ + "\"b\":\"bVal\""+ + "}"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + Object obj = jsonObject.query(new JSONPointer("/stringKey")); + assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); + obj = jsonObject.query(new JSONPointer("/arrayKey/1")); + assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); + obj = jsonObject.query(new JSONPointer("/objectKey/b")); + assertTrue("Expected bVal", "bVal".equals(obj)); + try { + obj = jsonObject.query(new JSONPointer("/a/b/c")); + assertTrue("Expected JSONPointerException", false); + } catch (JSONPointerException e) { + assertTrue("Expected bad key/value exception", + "value [null] is not an array or object therefore its key b cannot be resolved". + equals(e.getMessage())); + } + } + + /** + * Coverage for JSONObject optQuery(JSONPointer) + */ + @Test + public void optQueryFromJSONObjectUsingPointer() { + String str = "{"+ + "\"stringKey\":\"hello world!\","+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\": {"+ + "\"a\":\"aVal\","+ + "\"b\":\"bVal\""+ + "}"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + Object obj = jsonObject.optQuery(new JSONPointer("/stringKey")); + assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); + obj = jsonObject.optQuery(new JSONPointer("/arrayKey/1")); + assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); + obj = jsonObject.optQuery(new JSONPointer("/objectKey/b")); + assertTrue("Expected bVal", "bVal".equals(obj)); + obj = jsonObject.optQuery(new JSONPointer("/a/b/c")); + assertTrue("Expected null", obj == null); + } + + /** + * Coverage for JSONArray query(String) + */ + @Test + public void queryFromJSONArray() { + String str = "["+ + "\"hello world!\","+ + "[0,1,2],"+ + "{"+ + "\"a\":\"aVal\","+ + "\"b\":\"bVal\""+ + "}"+ + "]"; + JSONArray jsonArray = new JSONArray(str); + Object obj = jsonArray.query("/0"); + assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); + obj = jsonArray.query("/1/1"); + assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); + obj = jsonArray.query("/2/b"); + assertTrue("Expected bVal", "bVal".equals(obj)); + try { + obj = jsonArray.query("/a/b/c"); + assertTrue("Expected JSONPointerException", false); + } catch (JSONPointerException e) { + assertTrue("Expected bad index exception", + "a is not an array index".equals(e.getMessage())); + } + } + + /** + * Coverage for JSONArray query(JSONPointer) + */ + @Test + public void queryFromJSONArrayUsingPointer() { + String str = "["+ + "\"hello world!\","+ + "[0,1,2],"+ + "{"+ + "\"a\":\"aVal\","+ + "\"b\":\"bVal\""+ + "}"+ + "]"; + JSONArray jsonArray = new JSONArray(str); + Object obj = jsonArray.query(new JSONPointer("/0")); + assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); + obj = jsonArray.query(new JSONPointer("/1/1")); + assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); + obj = jsonArray.query(new JSONPointer("/2/b")); + assertTrue("Expected bVal", "bVal".equals(obj)); + try { + obj = jsonArray.query(new JSONPointer("/a/b/c")); + assertTrue("Expected JSONPointerException", false); + } catch (JSONPointerException e) { + assertTrue("Expected bad index exception", + "a is not an array index".equals(e.getMessage())); + } + } + + /** + * Coverage for JSONArray optQuery(JSONPointer) + */ + @Test + public void optQueryFromJSONArrayUsingPointer() { + String str = "["+ + "\"hello world!\","+ + "[0,1,2],"+ + "{"+ + "\"a\":\"aVal\","+ + "\"b\":\"bVal\""+ + "}"+ + "]"; + JSONArray jsonArray = new JSONArray(str); + Object obj = jsonArray.optQuery(new JSONPointer("/0")); + assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); + obj = jsonArray.optQuery(new JSONPointer("/1/1")); + assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); + obj = jsonArray.optQuery(new JSONPointer("/2/b")); + assertTrue("Expected bVal", "bVal".equals(obj)); + obj = jsonArray.optQuery(new JSONPointer("/a/b/c")); + assertTrue("Expected null", obj == null); + } + + /** + * When creating a jsonObject we need to parse escaped characters "\\\\" + * --> it's the string representation of "\\", so when query'ing via the JSONPointer + * we DON'T escape them + * + */ + @Test + public void queryFromJSONObjectUsingPointer0() { + String str = "{"+ + "\"string\\\\\\\\Key\":\"hello world!\","+ + + "\"\\\\\":\"slash test\"" + + "}"; + JSONObject jsonObject = new JSONObject(str); + //Summary of issue: When a KEY in the jsonObject is "\\\\" --> it's held + // as "\\" which means when querying, we need to use "\\" + Object twoBackslahObj = jsonObject.optQuery(new JSONPointer("/\\")); + assertEquals("slash test", twoBackslahObj); + + Object fourBackslashObj = jsonObject.optQuery(new JSONPointer("/string\\\\Key")); + assertEquals("hello world!", fourBackslashObj); + } +} From e5e97f87b116ccc85aa0bcef5a22903a2ef56739 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sun, 11 Oct 2026 11:36:41 -0500 Subject: [PATCH 28/33] Specify requirements for code changes and pull requests Added requirements for code changes and pull requests to ensure backward compatibility and proper issue reporting. --- README.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/README.md b/README.md index 2536343ec..08db835d8 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,24 @@ For more information on contributions, please see [CONTRIBUTING.md](https://gith Bug fixes, code improvements, and unit test coverage changes are welcome! Because this project is currently in the maintenance phase, the kinds of changes that can be accepted are limited. For more information, please read the [FAQ](https://github.com/stleary/JSON-java/wiki/FAQ). +The project has recently received a number of pull requests that each make a small change to existing behavior. Most come from reading the code or a specification, many apparently with the help of AI tools, and not from a problem that someone met in use. Each change is small, but together they put backward compatibility at risk. For that reason, the requirements below now apply. + +# Requirements for code changes + +These requirements apply to every pull request that changes code under src/main: + +**1. File an issue first.** The issue must come from someone who hit the problem in real use. It should describe what you were doing, the input, the result you got, and the result you expected. A difference from a specification that was found by reading the code is not enough on its own. + +**2. State which inputs change, and how.** The pull request description must link the issue and list the inputs that behave differently, with the result before and after the change. If no existing behavior changes, say so. + +Pull requests that do not meet these requirements may be closed without review. + +Pull requests that only change unit tests or documentation do not need an issue. Security vulnerabilities are handled separately; please report them as described in SECURITY.md. + +**JSONPointer is frozen** + +Several fixes that bring JSONPointer in line with RFC 6901 ship in the release that follows 20260814. Once that release is published, JSONPointer is frozen. It will be reopened only for bugs that users report, under the requirements above. Its behavior is pinned by JSONPointerConformanceTest (**TBD**). + # Build Instructions The org.json package can be built from the command line, Maven, and Gradle. The unit tests can be executed from Maven, Gradle, or individually in an IDE e.g. Eclipse. From 293bbf65d335921d56a840dd6b0d2840d4617c84 Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Tue, 20 Oct 2026 09:54:00 -0700 Subject: [PATCH 29/33] Share repeated object keys within a parse (#1091) --- src/main/java/org/json/JSONObject.java | 2 +- .../org/json/JSONParserConfiguration.java | 45 ++++++ src/main/java/org/json/JSONTokener.java | 30 ++++ .../junit/JSONParserConfigurationTest.java | 138 ++++++++++++++++++ 4 files changed, 214 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/json/JSONObject.java b/src/main/java/org/json/JSONObject.java index 3ded23f61..9029c8e66 100644 --- a/src/main/java/org/json/JSONObject.java +++ b/src/main/java/org/json/JSONObject.java @@ -276,7 +276,7 @@ private boolean parseJSONObject(JSONTokener jsonTokener, JSONParserConfiguration return true; default: obj = jsonTokener.nextSimpleValue(c); - key = obj.toString(); + key = jsonTokener.shareKey(obj.toString(), jsonParserConfiguration.getMaxSharedKeys()); } checkKeyForStrictMode(jsonTokener, jsonParserConfiguration, obj); diff --git a/src/main/java/org/json/JSONParserConfiguration.java b/src/main/java/org/json/JSONParserConfiguration.java index 0cfa2eaef..da5a66067 100644 --- a/src/main/java/org/json/JSONParserConfiguration.java +++ b/src/main/java/org/json/JSONParserConfiguration.java @@ -4,6 +4,16 @@ * Configuration object for the JSON parser. The configuration is immutable. */ public class JSONParserConfiguration extends ParserConfiguration { + /** + * The default maximum number of distinct object keys shared within one parse. + */ + public static final int DEFAULT_MAXIMUM_SHARED_KEYS = 1000; + + /** + * Used to indicate that there is no limit on the number of distinct object keys shared within one parse. + */ + public static final int UNLIMITED_SHARED_KEYS = -1; + /** * Used to indicate whether to overwrite duplicate key or not. */ @@ -14,12 +24,18 @@ public class JSONParserConfiguration extends ParserConfiguration { */ private boolean useNativeNulls; + /** + * The maximum number of distinct object keys shared within one parse. + */ + private int maxSharedKeys; + /** * Configuration with the default values. */ public JSONParserConfiguration() { super(); this.overwriteDuplicateKey = false; + this.maxSharedKeys = DEFAULT_MAXIMUM_SHARED_KEYS; // DO NOT DELETE THE FOLLOWING LINE -- it is used for strictMode testing // this.strictMode = true; } @@ -38,6 +54,7 @@ protected JSONParserConfiguration clone() { clone.maxNestingDepth = maxNestingDepth; clone.keepStrings = keepStrings; clone.useNativeNulls = useNativeNulls; + clone.maxSharedKeys = maxSharedKeys; return clone; } @@ -89,6 +106,24 @@ public JSONParserConfiguration withUseNativeNulls(final boolean useNativeNulls) return clone; } + /** + * Defines how many distinct object keys the parser shares within one parse. When a key repeats, for example + * in each element of an array of objects, the parser reuses the first String instance read for that key + * instead of keeping a separate copy in every object. Only the first maxSharedKeys distinct keys + * are shared, so input that begins with many unique keys may need a higher limit. The default is 1000. + * Parsed values are the same with any setting. + * + * @param maxSharedKeys the maximum number of distinct keys to share; 0 disables sharing, and + * {@link #UNLIMITED_SHARED_KEYS} (or any negative value) removes the limit + * @return The existing configuration will not be modified. A new configuration is returned. + */ + public JSONParserConfiguration withMaxSharedKeys(final int maxSharedKeys) { + JSONParserConfiguration clone = this.clone(); + clone.maxSharedKeys = Math.max(maxSharedKeys, UNLIMITED_SHARED_KEYS); + + return clone; + } + /** * Sets the strict mode configuration for the JSON parser with default true value *

@@ -140,6 +175,16 @@ public boolean isUseNativeNulls() { } + /** + * The maximum number of distinct object keys shared within one parse. 0 means keys are not shared, + * and {@link #UNLIMITED_SHARED_KEYS} means there is no limit. + * + * @return The maxSharedKeys configuration value. + */ + public int getMaxSharedKeys() { + return this.maxSharedKeys; + } + /** * The parser throws an Exception when strict mode is true and tries to parse invalid JSON characters. * Otherwise, the parser is more relaxed and might tolerate some invalid characters. diff --git a/src/main/java/org/json/JSONTokener.java b/src/main/java/org/json/JSONTokener.java index 1acb73bf7..56d97cd19 100644 --- a/src/main/java/org/json/JSONTokener.java +++ b/src/main/java/org/json/JSONTokener.java @@ -2,6 +2,8 @@ import java.io.*; import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Map; /* Public Domain. @@ -35,6 +37,9 @@ public class JSONTokener { // access to this object is required for strict mode checking private JSONParserConfiguration jsonParserConfiguration; + /** object keys already read, so repeated keys can share one String instance. */ + private Map sharedKeys; + /** * Construct a JSONTokener from a Reader. The caller must close the Reader. * @@ -124,6 +129,31 @@ void setJsonParserConfigurationInternal(JSONParserConfiguration jsonParserConfig this.jsonParserConfiguration = jsonParserConfiguration; } + /** + * Returns an earlier String instance equal to the key if this tokener has read one, otherwise the key itself. + * + * @param key an object key that was just read + * @param maxSharedKeys the maximum number of distinct keys to remember; 0 disables sharing and a negative + * value means no limit + * @return a String equal to key + */ + String shareKey(String key, int maxSharedKeys) { + if (maxSharedKeys == 0) { + return key; + } + if (this.sharedKeys == null) { + this.sharedKeys = new HashMap(); + } + String shared = this.sharedKeys.get(key); + if (shared != null) { + return shared; + } + if (maxSharedKeys < 0 || this.sharedKeys.size() < maxSharedKeys) { + this.sharedKeys.put(key, key); + } + return key; + } + /** * Back up one character. This provides a sort of lookahead capability, * so that you can test for a digit or letter before attempting to parse diff --git a/src/test/java/org/json/junit/JSONParserConfigurationTest.java b/src/test/java/org/json/junit/JSONParserConfigurationTest.java index 21bb84115..d974d9374 100644 --- a/src/test/java/org/json/junit/JSONParserConfigurationTest.java +++ b/src/test/java/org/json/junit/JSONParserConfigurationTest.java @@ -16,9 +16,11 @@ import java.util.stream.Stream; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; public class JSONParserConfigurationTest { @@ -708,4 +710,140 @@ private List getNonCompliantJSONObjectList() { ); } + private static final String SHARED_KEYS_SOURCE = "{\"rows\": [" + + "{\"name\": \"a\", \"count\": 1, \"big\": 12345678901, \"ratio\": 1.5, \"flag\": true, \"missing\": null," + + " \"nested\": {\"name\": \"inner\", \"list\": [1, \"name\", null]}}," + + "{\"name\": \"name\", \"count\": 2, \"nested\": {\"name\": \"inner2\", \"list\": []}}," + + "{\"name\": \"third\", \"count\": -3}" + + "]}"; + + @Test + public void testMaxSharedKeysConfig() { + JSONParserConfiguration config = new JSONParserConfiguration(); + assertEquals(JSONParserConfiguration.DEFAULT_MAXIMUM_SHARED_KEYS, config.getMaxSharedKeys()); + assertEquals(1000, config.getMaxSharedKeys()); + assertEquals(0, config.withMaxSharedKeys(0).getMaxSharedKeys()); + assertEquals(JSONParserConfiguration.UNLIMITED_SHARED_KEYS, config.withMaxSharedKeys(-1).getMaxSharedKeys()); + assertEquals(JSONParserConfiguration.UNLIMITED_SHARED_KEYS, config.withMaxSharedKeys(-5).getMaxSharedKeys()); + + JSONParserConfiguration chained = config.withMaxSharedKeys(7).withOverwriteDuplicateKey(true).withStrictMode(false); + assertEquals(7, chained.getMaxSharedKeys()); + assertTrue(chained.isOverwriteDuplicateKey()); + assertEquals(1000, config.getMaxSharedKeys()); + } + + @Test + public void testSharedKeysByDefault() { + JSONArray rows = new JSONObject(SHARED_KEYS_SOURCE).getJSONArray("rows"); + String nameKey = key(rows.getJSONObject(0), "name"); + for (int i = 1; i < rows.length(); i++) { + assertSame(nameKey, key(rows.getJSONObject(i), "name")); + } + assertSame(nameKey, key(rows.getJSONObject(0).getJSONObject("nested"), "name")); + assertSame(key(rows.getJSONObject(0), "count"), key(rows.getJSONObject(2), "count")); + assertSame(key(rows.getJSONObject(0).getJSONObject("nested"), "list"), + key(rows.getJSONObject(1).getJSONObject("nested"), "list")); + + // string values equal to a key are not shared + assertNotSame(nameKey, rows.getJSONObject(1).get("name")); + assertNotSame(nameKey, rows.getJSONObject(0).getJSONObject("nested").getJSONArray("list").get(1)); + } + + @Test + public void testSharedKeysDisabled() { + JSONArray rows = new JSONObject(SHARED_KEYS_SOURCE, new JSONParserConfiguration().withMaxSharedKeys(0)) + .getJSONArray("rows"); + assertNotSame(key(rows.getJSONObject(0), "name"), key(rows.getJSONObject(1), "name")); + assertNotSame(key(rows.getJSONObject(0), "count"), key(rows.getJSONObject(1), "count")); + } + + @Test + public void testSharedKeysLimit() { + JSONArray rows = new JSONArray("[{\"a\": 1, \"b\": 2, \"c\": 3}, {\"a\": 4, \"b\": 5, \"c\": 6}]", + new JSONParserConfiguration().withMaxSharedKeys(2)); + assertSame(key(rows.getJSONObject(0), "a"), key(rows.getJSONObject(1), "a")); + assertSame(key(rows.getJSONObject(0), "b"), key(rows.getJSONObject(1), "b")); + assertNotSame(key(rows.getJSONObject(0), "c"), key(rows.getJSONObject(1), "c")); + } + + @Test + public void testSharedKeysUnlimited() { + int keyCount = JSONParserConfiguration.DEFAULT_MAXIMUM_SHARED_KEYS + 500; + StringBuilder row = new StringBuilder("{"); + for (int i = 0; i < keyCount; i++) { + row.append(i == 0 ? "" : ",").append("\"k").append(i).append("\":").append(i); + } + row.append('}'); + String source = "[" + row + "," + row + "]"; + + JSONArray unlimited = new JSONArray(source, + new JSONParserConfiguration().withMaxSharedKeys(JSONParserConfiguration.UNLIMITED_SHARED_KEYS)); + for (int i = 0; i < keyCount; i++) { + assertSame(key(unlimited.getJSONObject(0), "k" + i), key(unlimited.getJSONObject(1), "k" + i)); + } + + JSONArray limited = new JSONArray(source); + String lastKey = "k" + (keyCount - 1); + assertSame(key(limited.getJSONObject(0), "k0"), key(limited.getJSONObject(1), "k0")); + assertNotSame(key(limited.getJSONObject(0), lastKey), key(limited.getJSONObject(1), lastKey)); + assertTrue(unlimited.similar(limited)); + } + + @Test + public void testSharedKeysNotSharedAcrossParses() { + JSONObject first = new JSONObject("{\"name\": 1}"); + JSONObject second = new JSONObject("{\"name\": 2}"); + assertNotSame(key(first, "name"), key(second, "name")); + } + + @Test + public void testSharedKeysParseUnchanged() { + JSONObject unshared = new JSONObject(SHARED_KEYS_SOURCE, new JSONParserConfiguration().withMaxSharedKeys(0)); + JSONObject shared = new JSONObject(SHARED_KEYS_SOURCE); + JSONObject unlimited = new JSONObject(SHARED_KEYS_SOURCE, + new JSONParserConfiguration().withMaxSharedKeys(JSONParserConfiguration.UNLIMITED_SHARED_KEYS)); + assertTrue(unshared.similar(shared)); + assertTrue(unshared.similar(unlimited)); + assertEquals(unshared.toString(), shared.toString()); + assertEquals(unshared.toString(), unlimited.toString()); + + JSONObject row = shared.getJSONArray("rows").getJSONObject(0); + assertEquals(Integer.class, row.get("count").getClass()); + assertEquals(Long.class, row.get("big").getClass()); + assertEquals(java.math.BigDecimal.class, row.get("ratio").getClass()); + assertEquals(Boolean.TRUE, row.get("flag")); + assertSame(JSONObject.NULL, row.get("missing")); + assertSame(JSONObject.NULL, row.getJSONObject("nested").getJSONArray("list").get(2)); + assertEquals("third", shared.getJSONArray("rows").getJSONObject(2).get("name")); + } + + @Test + public void testSharedKeysLenientSyntax() { + JSONArray rows = new JSONArray("[{\"name\": 1, \"count\": 2}, {'name': 'single', count: 3}]", + new JSONParserConfiguration().withStrictMode(false)); + assertSame(key(rows.getJSONObject(0), "name"), key(rows.getJSONObject(1), "name")); + assertSame(key(rows.getJSONObject(0), "count"), key(rows.getJSONObject(1), "count")); + assertEquals("single", rows.getJSONObject(1).get("name")); + } + + @Test + public void testSharedKeysStrictMode() { + JSONArray rows = new JSONArray("[{\"a\": 1}, {\"a\": 2}]", new JSONParserConfiguration().withStrictMode()); + assertSame(key(rows.getJSONObject(0), "a"), key(rows.getJSONObject(1), "a")); + assertFalse(rows.getJSONObject(0).similar(rows.getJSONObject(1))); + } + + /** + * Returns the key instance a JSONObject holds, rather than the caller's equal String. + */ + private static String key(JSONObject jsonObject, String name) { + for (String key : jsonObject.keySet()) { + if (key.equals(name)) { + return key; + } + } + fail("missing key " + name); + return null; + } + } From fea3a2ce32a63c249a20e1a6477ec0881d767103 Mon Sep 17 00:00:00 2001 From: Lyin-OTTF Date: Tue, 20 Oct 2026 13:29:07 +0000 Subject: [PATCH 30/33] Escape TAB/LF/CR again when serializing to XML XML.mustEscape() is shared by XML.escape() (serialization) and XMLTokener.unescapeEntity() (parsing), but the two callers need opposite answers for #x9/#xA/#xD. #1070 added those codepoints to the valid-range clause to fix unescape(" "), which also stopped XML.toString() and JSONML.toString() from escaping literal TAB, LF and CR. Literal occurrences of these characters are subject to whitespace normalization by conforming XML parsers, so a value like "Lettuce\nTomato" loses its line breaks when the generated XML is read back by any standard parser. This regressed #1092. Split the two concerns: mustEscape() returns true for every ISO control character again (serialization), and the new isValidXmlCharacter() keeps the previous numeric-reference validation for the parsing path, so , and are still accepted (#1059/#1070 behaviour unchanged). isValidXmlCharacter() stays as strict as before for the C1 control characters (#x7F-#x9F): they fall inside [#x20-#xD7FF] and are legal XML 1.0 characters, but this library has always rejected references to them, and widening the range here would silently change what XML.toJSONObject accepts. Only the serialization of TAB/LF/CR changes. Fixes #1092 --- src/main/java/org/json/XML.java | 51 +++++++++------- src/main/java/org/json/XMLTokener.java | 6 +- src/test/java/org/json/junit/XMLTest.java | 71 +++++++++++++++++++++++ 3 files changed, 107 insertions(+), 21 deletions(-) diff --git a/src/main/java/org/json/XML.java b/src/main/java/org/json/XML.java index b3d05ebec..70386be2e 100644 --- a/src/main/java/org/json/XML.java +++ b/src/main/java/org/json/XML.java @@ -156,34 +156,45 @@ public static String escape(String string) { /** * @param cp code point to test - * @return true if the code point is not valid for an XML + * @return true if the code point must be escaped when serializing to XML */ static boolean mustEscape(int cp) { + // Every ISO control character must be written as a numeric character + // reference when serializing. This includes #x9 (tab), #xA (LF) and + // #xD (CR): literal occurrences of these characters are subject to + // whitespace normalization by conforming XML parsers, so they can + // only survive a round trip as , and (see #1092). + // + // This method is only about the serialization path. Numeric character + // references found while parsing are validated with + // isValidXmlCharacter(int) (see #1059). + return Character.isISOControl(cp) || !isValidXmlCharacter(cp); + } + + /** + * @param cp code point to test + * @return true if the code point can be written as a numeric character + * reference in a document generated by this class + */ + static boolean isValidXmlCharacter(int cp) { /* Valid range from https://www.w3.org/TR/REC-xml/#charsets * * #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] * * any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */ - // isISOControl is true when (cp >= 0 && cp <= 0x1F) || (cp >= 0x7F && cp <= 0x9F) - // all ISO control characters are out of range except tabs and new lines - return (Character.isISOControl(cp) - && cp != 0x9 - && cp != 0xA - && cp != 0xD - ) || !( - // Valid character range per W3C XML 1.0 spec: - // #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] - // Previously omitted #x9/#xA/#xD, causing unescape(" ") etc. - // to reject valid LF/TAB/CR as illegal (see #1059) - cp == 0x9 - || cp == 0xA - || cp == 0xD - || (cp >= 0x20 && cp <= 0xD7FF) - || (cp >= 0xE000 && cp <= 0xFFFD) - || (cp >= 0x10000 && cp <= 0x10FFFF) - ) - ; + // The C1 control characters (#x7F-#x9F) fall inside [#x20-#xD7FF] and + // are therefore legal XML 1.0 characters, but this class has always + // rejected &#NN; references to them while parsing. Keeping them + // rejected here keeps the parse result of this fix identical to the + // previous release; accepting them would be a separate behaviour + // change (see #1093). + if (Character.isISOControl(cp)) { + return cp == 0x9 || cp == 0xA || cp == 0xD; + } + return (cp >= 0x20 && cp <= 0xD7FF) + || (cp >= 0xE000 && cp <= 0xFFFD) + || (cp >= 0x10000 && cp <= 0x10FFFF); } /** diff --git a/src/main/java/org/json/XMLTokener.java b/src/main/java/org/json/XMLTokener.java index dc90f84d4..ca50625a0 100644 --- a/src/main/java/org/json/XMLTokener.java +++ b/src/main/java/org/json/XMLTokener.java @@ -167,7 +167,11 @@ static String unescapeEntity(String e) throws JSONException { int cp = (e.charAt(1) == 'x' || e.charAt(1) == 'X') ? parseHexEntity(e) : parseDecimalEntity(e); - if (XML.mustEscape(cp)) { + // Validate with isValidXmlCharacter, not with XML.mustEscape: + // mustEscape also escapes TAB/LF/CR for the serialization path + // (#1092), while the numeric references , and are + // valid XML and must keep being accepted here (see #1059). + if (!XML.isValidXmlCharacter(cp)) { throw new JSONException("Invalid numeric character reference: &#" + e.substring(1) + ";"); } return new String(new int[] {cp}, 0, 1); diff --git a/src/test/java/org/json/junit/XMLTest.java b/src/test/java/org/json/junit/XMLTest.java index 0533673cf..4268748fa 100644 --- a/src/test/java/org/json/junit/XMLTest.java +++ b/src/test/java/org/json/junit/XMLTest.java @@ -7,6 +7,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -1610,6 +1611,76 @@ public void testValidWhitespaceNumericEntityToJSONObject() { XML.toJSONObject(" "); } + /** + * Tests that numeric character references to C1 control characters are + * still rejected. #x7F-#x9F is inside the XML 1.0 {@code Char} range, but + * this library has always refused those references while parsing + * ({@code …} is NEL, #x85), and fixing the serialization of TAB/LF/CR + * must not change what the parser accepts. + */ + @Test + public void testRejectsC1ControlCharacterReference() { + assertThrows(JSONException.class, + () -> XML.toJSONObject("Joe … Tester")); + // the neighbouring boundary codepoints behave the same way + assertThrows(JSONException.class, + () -> XML.toJSONObject("Joe  Tester")); + assertThrows(JSONException.class, + () -> XML.toJSONObject("Joe Ÿ Tester")); + // ... while the characters the parser does accept still work + XML.toJSONObject("Joe Tester"); + } + + /** + * Tests that serializing a string value containing literal TAB, LF and CR + * characters writes numeric character references (&#9;, &#10;, + * &#13;) instead of the literal characters. Literal occurrences of + * these characters are subject to whitespace normalization by conforming + * XML parsers, so the original value would be lost when the generated XML + * is read back. Regression test for #1092, where #1070 stopped + * XML.toString() and JSONML.toString() from escaping these characters. + */ + @Test + public void testEscapesLiteralWhitespaceControlCharsOnSerialization() { + // LF in a text node must survive as a numeric character reference + JSONObject jo = new JSONObject().put("value", "Lettuce\nTomato"); + String xmlOutput = XML.toString(jo); + assertTrue("XML should escape literal LF to preserve it, got: " + xmlOutput, + xmlOutput.contains(" ")); + + // TAB and CR likewise + JSONObject tabJo = new JSONObject().put("value", "a\tb\rc"); + String tabXml = XML.toString(tabJo); + assertTrue("XML should escape literal TAB, got: " + tabXml, tabXml.contains(" ")); + assertTrue("XML should escape literal CR, got: " + tabXml, tabXml.contains(" ")); + } + + /** + * Tests that the generated XML round-trips: the numeric character + * references produced for TAB/LF/CR are read back by + * {@code XML.toJSONObject} as the original characters. + */ + @Test + public void testWhitespaceControlCharsRoundTripThroughXml() { + String original = "Lettuce\nTomato\tMustard"; + JSONObject jo = new JSONObject().put("value", original); + String xmlOutput = XML.toString(jo); + JSONObject reparsed = XML.toJSONObject(xmlOutput); + assertEquals("LF/TAB must survive the XML round trip", + original, reparsed.getString("value")); + } + + /** + * Same escaping requirement for {@code JSONML.toString}. + */ + @Test + public void testJSONMLToStringEscapesLiteralNewlines() { + JSONObject jo = new JSONObject("{\"tagName\":\"MyTag\", \"value\":\"Lettuce\\nTomato\"}"); + String xmlOutput = JSONML.toString(jo); + assertTrue("JSONML should escape literal LF to preserve it, got: " + xmlOutput, + xmlOutput.contains(" ")); + } + } From 88b6be9f84cd39e38166950797fa0358f8bad2ff Mon Sep 17 00:00:00 2001 From: Lyin-OTTF Date: Tue, 20 Oct 2026 23:36:08 +0800 Subject: [PATCH 31/33] Clarify fromJson(Class) Javadoc: type registry does not exist The fromJson(Class) Javadoc claimed that only classes "explicitly supported and registered within the JSONObject context" can be deserialized, and declared an IllegalArgumentException for classes outside that set. No such registry exists: fromJson instantiates any class with a no-arg constructor and writes every non-static declared field whose name matches a JSON key, widening access with setAccessible(true). Private and transient fields are populated, and JSONPropertyIgnore does not apply because it only suppresses the bean to JSONObject direction. The binding rules are already released, so changing them here would break existing users. Instead document what actually happens, point out that binding is driven by whatever keys the JSON contains, and replace the non-existent IllegalArgumentException with the JSONException the method really throws. Adds JSONObjectTest#jsonObjectParseFromJson_10 to pin the current binding behavior so the documentation cannot drift from the implementation again. The test bean is named FromJsonKeyBindingExample and its fields spell out how they are declared (privateString, privateBoolean, transientString, ignoredGetterBoolean), so the test reads as a binding example rather than as a scenario. Fixes #1076 --- src/main/java/org/json/JSONObject.java | 20 +++++++--- .../java/org/json/junit/JSONObjectTest.java | 26 +++++++++++++ .../junit/data/FromJsonKeyBindingExample.java | 39 +++++++++++++++++++ 3 files changed, 79 insertions(+), 6 deletions(-) create mode 100644 src/test/java/org/json/junit/data/FromJsonKeyBindingExample.java diff --git a/src/main/java/org/json/JSONObject.java b/src/main/java/org/json/JSONObject.java index 3ded23f61..1c329e174 100644 --- a/src/main/java/org/json/JSONObject.java +++ b/src/main/java/org/json/JSONObject.java @@ -3472,12 +3472,15 @@ private Type[] getMapTypes(Type type) { * of the given class. It supports basic data types including int, double, float, * long, and boolean (as well as their boxed counterparts). The class must have a * no-argument constructor, and the field names in the class must match the keys - * in the JSON string. + * in the JSON string. Static fields are ignored; see {@link #fromJson(Class)} for + * how the remaining fields are bound. * * @param the type of the object to return * @param jsonString json in string format * @param clazz the class of the object to be returned * @return an instance of Object T with fields populated from the JSON string + * @throws JSONException if jsonString is not valid JSON, or if it cannot be bound to clazz + * as described in {@link #fromJson(Class)} */ public static T fromJson(String jsonString, Class clazz) { JSONObject jsonObject = new JSONObject(jsonString); @@ -3493,15 +3496,20 @@ public static T fromJson(String jsonString, Class clazz) { * The target class must have a no-argument constructor, and its field names must match * the keys in the JSON string. Static fields are ignored. * - *

Note: Only classes that are explicitly supported and registered within - * the {@code JSONObject} context can be deserialized. If the provided class is not among those, - * this method will not be able to deserialize it. This ensures that only a limited and - * controlled set of types can be instantiated from JSON for safety and predictability. + *

Note: binding is driven by the keys present in the JSON, not by + * how the fields are declared. Every non-static field declared by the class is written + * when its name matches a key, including {@code private} and {@code transient} fields, + * and field access is widened with + * {@link java.lang.reflect.Field#setAccessible(boolean)}. {@link JSONPropertyIgnore} + * only suppresses the bean to JSONObject direction, so it does not keep a field from + * being populated here. JSON coming from an untrusted source should therefore be + * validated, or reduced to the expected keys, before it is handed to this method. * * @param clazz the class of the object to be returned * @param the type of the object * @return an instance of type {@code T} with fields populated from the JSON string - * @throws IllegalArgumentException if the class is not supported for deserialization + * @throws JSONException if the class has no accessible no-argument constructor, or if a + * field cannot be instantiated or set */ @SuppressWarnings("unchecked") public T fromJson(Class clazz) { diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index a0f0638b0..ecc3204e7 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -67,6 +67,7 @@ import org.json.junit.data.CustomClassH; import org.json.junit.data.CustomClassI; import org.json.junit.data.CustomClassJ; +import org.json.junit.data.FromJsonKeyBindingExample; import org.junit.After; import org.junit.Ignore; import org.junit.Test; @@ -3883,6 +3884,31 @@ public void jsonObjectParseFromJson_9() { } } + /** + * Pins down the field binding done by {@code fromJson(Class)}: every non-static + * declared field whose name matches a JSON key is written, no matter how the + * field is declared. Private fields, transient fields and fields hidden behind + * a {@code @JSONPropertyIgnore} getter are all populated, because that + * annotation only affects the bean to JSONObject direction. See issue #1076. + */ + @Test + public void jsonObjectParseFromJson_10() { + JSONObject object = new JSONObject() + .put("displayName", "bob") + .put("privateBoolean", true) + .put("privateString", "private-value") + .put("transientString", "transient-value") + .put("ignoredGetterBoolean", true); + + FromJsonKeyBindingExample bound = object.fromJson(FromJsonKeyBindingExample.class); + + assertEquals("private field should be populated", true, bound.isPrivateBoolean()); + assertEquals("private field should be populated", "private-value", bound.getPrivateString()); + assertEquals("transient field should be populated", "transient-value", bound.getTransientString()); + assertEquals("field behind a @JSONPropertyIgnore getter should be populated", true, + bound.isIgnoredGetterBoolean()); + } + @Test public void testMaxNumberLength() { JSONParserConfiguration jsonParserConfiguration = new JSONParserConfiguration(); diff --git a/src/test/java/org/json/junit/data/FromJsonKeyBindingExample.java b/src/test/java/org/json/junit/data/FromJsonKeyBindingExample.java new file mode 100644 index 000000000..5d281424f --- /dev/null +++ b/src/test/java/org/json/junit/data/FromJsonKeyBindingExample.java @@ -0,0 +1,39 @@ +package org.json.junit.data; + +import org.json.JSONPropertyIgnore; + +/** + * Bean used to pin down how {@code JSONObject#fromJson(Class)} binds JSON keys + * to fields: {@code privateString} and {@code privateBoolean} are private, + * {@code transientString} is transient, and {@code ignoredGetterBoolean} is + * hidden behind a getter annotated with {@code @JSONPropertyIgnore} (which only + * suppresses the bean to JSONObject direction). + */ +public class FromJsonKeyBindingExample { + public String displayName; + private boolean privateBoolean; + private String privateString; + private transient String transientString; + private boolean ignoredGetterBoolean; + + public FromJsonKeyBindingExample() { + // Required for JSONObject#fromJson(Class) tests. + } + + public boolean isPrivateBoolean() { + return privateBoolean; + } + + public String getPrivateString() { + return privateString; + } + + public String getTransientString() { + return transientString; + } + + @JSONPropertyIgnore + public boolean isIgnoredGetterBoolean() { + return ignoredGetterBoolean; + } +} From f607f7cc09c35eb0fb129a71ccbba204d9735a36 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sat, 21 Nov 2026 12:06:21 -0600 Subject: [PATCH 32/33] Enhance SECURITY.md with key expiration details Added troubleshooting section for expired keys and clarified key expiration handling. --- docs/SECURITY.md | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 3a1e60ebe..f33297a98 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -14,6 +14,7 @@ All releases of `org.json:json` published to Maven Central are signed with PGP. | --- | --- | | **Fingerprint** | `FB35 C8D0 2B47 24DA DA23 DE0A FD11 6C19 69FC CFF3` | | **Long key ID** | `FD116C1969FCCFF3` | +| **Expires**. | `2035-12-12 | | **Keyserver** | `hkps://keyserver.ubuntu.com` | The full 40-character fingerprint above is the canonical identifier for the key. Always pin or compare against the full fingerprint rather than the long or short key ID. @@ -55,6 +56,22 @@ If you are using Gradle's [dependency verification](https://docs.gradle.org/curr Gradle also accepts the long key ID (`FD116C1969FCCFF3`), but pinning the full fingerprint is recommended. +### Troubleshooting: Expired Key (`EXPKEYSIG`) + +If GPG reports `EXPKEYSIG` or says the key has expired, your local copy of the public key is likely out of date. The key's expiration date is extended periodically; extending it does not change the fingerprint, and signatures on earlier releases remain valid. Refresh the key from the keyserver and verify again. For example: + +```bash +gpg --keyserver hkps://keyserver.ubuntu.com \ + --refresh-keys FB35C8D02B4724DADA23DE0AFD116C1969FCCFF3 +gpg --verify json-20260814.jar.asc json-20260814.jar +``` + +If you use Gradle dependency verification with a cached keyring, regenerate it after refreshing. For example: + +`./gradlew --write-verification-metadata pgp,sha256 --export-keys help` + +If the expiration date shown by `gpg --list-keys` after refreshing does not match the date in the table above, please open an issue. + ### Key Rotation -If the signing key is ever rotated or revoked, this document will be updated in the `master` branch with the new fingerprint, and the change will be visible in the file's commit history. Always check this file directly in the repository for the current authoritative value before trusting any third-party copy of the fingerprint. \ No newline at end of file +If the signing key's expiration date is extended, the **Expires** value above will be updated and the refreshed public key will be published to the keyserver; the fingerprint stays the same. If the signing key is ever rotated or revoked, this document will be updated in the `master` branch with the new fingerprint, and the change will be visible in the file's commit history. Always check this file directly in the repository for the current authoritative value before trusting any third-party copy of the fingerprint. From 1582e72dc54001f5c3847f64acb3209191dbe00d Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sat, 21 Nov 2026 12:06:39 -0600 Subject: [PATCH 33/33] Fix formatting issue in SECURITY.md --- docs/SECURITY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index f33297a98..6ddbc68d6 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -14,7 +14,7 @@ All releases of `org.json:json` published to Maven Central are signed with PGP. | --- | --- | | **Fingerprint** | `FB35 C8D0 2B47 24DA DA23 DE0A FD11 6C19 69FC CFF3` | | **Long key ID** | `FD116C1969FCCFF3` | -| **Expires**. | `2035-12-12 | +| **Expires**. | `2035-12-12` | | **Keyserver** | `hkps://keyserver.ubuntu.com` | The full 40-character fingerprint above is the canonical identifier for the key. Always pin or compare against the full fingerprint rather than the long or short key ID.