From b5bcb68968f0f3f20598ca930e108a8657ba0c2d Mon Sep 17 00:00:00 2001 From: Zach Date: Wed, 17 Nov 2021 16:57:41 -0600 Subject: [PATCH] added set check logic --- src/main/java/org/json/JSONObject.java | 27 ++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/main/java/org/json/JSONObject.java b/src/main/java/org/json/JSONObject.java index 8891673..c1e3b70 100644 --- a/src/main/java/org/json/JSONObject.java +++ b/src/main/java/org/json/JSONObject.java @@ -39,6 +39,7 @@ import java.math.BigInteger; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; import java.util.Locale; import java.util.Map; @@ -1510,6 +1511,11 @@ public class JSONObject { return NULL.equals(object) ? defaultValue : object.toString(); } + // Set to store the current seen objects in the recursive reaversal + // If the next value to be added to this set is a duplicate, a cycle + // is found + private final Set objectsRecord = new HashSet(); + /** * Populates the internal map of the JSONObject with the bean properties. The * bean can not be recursive. @@ -1541,8 +1547,18 @@ public class JSONObject { final Object result = method.invoke(bean); if (result != null) { // check cyclic dependency and throw error if needed + // the wrap and populateMap combination method is + // itself DFS recursive + if (objectsRecord.contains(result)) { + throw recursivelyDefinedObjectException(key); + } + + objectsRecord.add(result); this.map.put(key, wrap(result)); + + objectsRecord.remove(result); + // we don't use the result anywhere outside of wrap // if it's a resource we should be sure to close it // after calling toString @@ -2678,4 +2694,15 @@ public class JSONObject { "JSONObject[" + quote(key) + "] is not a " + valueType + " (" + value + ")." , cause); } + + /** + * Create a new JSONException in a common format for recursive object definition. + * @param key name of the key + * @return JSONException that can be thrown. + */ + private static JSONException recursivelyDefinedObjectException(String key) { + return new JSONException( + "JavaBean object contains recursively defined member variable of key " + quote(key) + ); + } }