mirror of
https://github.com/stleary/JSON-java.git
synced 2025-08-02 11:05:28 -04:00
added set check logic
This commit is contained in:
parent
7823d3a4f3
commit
b5bcb68968
@ -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<Object> objectsRecord = new HashSet<Object>();
|
||||
|
||||
/**
|
||||
* 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)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user