@@ -232,7 +232,7 @@ public static void noSpace(String string) throws JSONException {
232232 * @return true if the close tag is processed.
233233 * @throws JSONException
234234 */
235- private static boolean parse (XMLTokener x , JSONObject context , String name , XMLParserConfiguration config )
235+ private static boolean parse (XMLTokener x , JSONObject context , String name , XMLParserConfiguration config , int currentNestingDepth )
236236 throws JSONException {
237237 char c ;
238238 int i ;
@@ -402,7 +402,11 @@ private static boolean parse(XMLTokener x, JSONObject context, String name, XMLP
402402
403403 } else if (token == LT ) {
404404 // Nested element
405- if (parse (x , jsonObject , tagName , config )) {
405+ if (currentNestingDepth == config .getMaxNestingDepth ()) {
406+ throw x .syntaxError ("Maximum nesting depth of " + config .getMaxNestingDepth () + " reached" );
407+ }
408+
409+ if (parse (x , jsonObject , tagName , config , currentNestingDepth + 1 )) {
406410 if (config .getForceList ().contains (tagName )) {
407411 // Force the value to be an array
408412 if (jsonObject .length () == 0 ) {
@@ -644,6 +648,10 @@ public static JSONObject toJSONObject(Reader reader, boolean keepStrings) throws
644648 * All values are converted as strings, for 1, 01, 29.0 will not be coerced to
645649 * numbers but will instead be the exact value as seen in the XML document.
646650 *
651+ * This method can parse documents with a maximum nesting depth of 256. If you
652+ * need to parse documents with a nesting depth greater than 256, you should use
653+ *
654+ *
647655 * @param reader The XML source reader.
648656 * @param config Configuration options for the parser
649657 * @return A JSONObject containing the structured data from the XML string.
@@ -655,7 +663,7 @@ public static JSONObject toJSONObject(Reader reader, XMLParserConfiguration conf
655663 while (x .more ()) {
656664 x .skipPast ("<" );
657665 if (x .more ()) {
658- parse (x , jo , null , config );
666+ parse (x , jo , null , config , 0 );
659667 }
660668 }
661669 return jo ;
0 commit comments