added set check logic

This commit is contained in:
Zach 2021-11-17 16:57:41 -06:00
parent 7823d3a4f3
commit b5bcb68968

View File

@ -39,6 +39,7 @@ import java.math.BigInteger;
import java.util.Collection; import java.util.Collection;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
@ -1510,6 +1511,11 @@ public class JSONObject {
return NULL.equals(object) ? defaultValue : object.toString(); 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<Object> objectsRecord = new HashSet<Object>();
/** /**
* Populates the internal map of the JSONObject with the bean properties. The * Populates the internal map of the JSONObject with the bean properties. The
* bean can not be recursive. * bean can not be recursive.
@ -1541,8 +1547,18 @@ public class JSONObject {
final Object result = method.invoke(bean); final Object result = method.invoke(bean);
if (result != null) { if (result != null) {
// check cyclic dependency and throw error if needed // 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)); this.map.put(key, wrap(result));
objectsRecord.remove(result);
// we don't use the result anywhere outside of wrap // we don't use the result anywhere outside of wrap
// if it's a resource we should be sure to close it // if it's a resource we should be sure to close it
// after calling toString // after calling toString
@ -2678,4 +2694,15 @@ public class JSONObject {
"JSONObject[" + quote(key) + "] is not a " + valueType + " (" + value + ")." "JSONObject[" + quote(key) + "] is not a " + valueType + " (" + value + ")."
, cause); , 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)
);
}
} }