@@ -366,6 +366,11 @@ public JSONObject(Object bean) {
366366 this .populateMap (bean );
367367 }
368368
369+ private JSONObject (Object bean , Set <Object > objectsRecord ) {
370+ this ();
371+ this .populateMap (bean , objectsRecord );
372+ }
373+
369374 /**
370375 * Construct a JSONObject from an Object, using reflection to find the
371376 * public members. The resulting JSONObject's keys will be the strings from
@@ -1511,11 +1516,6 @@ public String optString(String key, String defaultValue) {
15111516 return NULL .equals (object ) ? defaultValue : object .toString ();
15121517 }
15131518
1514- // Set to store the current seen objects in the recursive reaversal
1515- // If the next value to be added to this set is a duplicate, a cycle
1516- // is found
1517- private final Set <Object > objectsRecord = new HashSet <Object >();
1518-
15191519 /**
15201520 * Populates the internal map of the JSONObject with the bean properties. The
15211521 * bean can not be recursive.
@@ -1526,6 +1526,10 @@ public String optString(String key, String defaultValue) {
15261526 * the bean
15271527 */
15281528 private void populateMap (Object bean ) {
1529+ populateMap (bean , new HashSet <Object >());
1530+ }
1531+
1532+ private void populateMap (Object bean , Set <Object > objectsRecord ) {
15291533 Class <?> klass = bean .getClass ();
15301534
15311535 // If klass is a System class then set includeSuperClass to false.
@@ -1555,7 +1559,7 @@ && isValidMethodName(method.getName())) {
15551559
15561560 objectsRecord .add (result );
15571561
1558- this .map .put (key , wrap (result ));
1562+ this .map .put (key , wrap (result , objectsRecord ));
15591563
15601564 objectsRecord .remove (result );
15611565
@@ -2449,6 +2453,10 @@ public static String valueToString(Object value) throws JSONException {
24492453 * @return The wrapped value
24502454 */
24512455 public static Object wrap (Object object ) {
2456+ return wrap (object , null );
2457+ }
2458+
2459+ private static Object wrap (Object object , Set <Object > objectsRecord ) {
24522460 try {
24532461 if (NULL .equals (object )) {
24542462 return NULL ;
@@ -2483,7 +2491,15 @@ public static Object wrap(Object object) {
24832491 || object .getClass ().getClassLoader () == null ) {
24842492 return object .toString ();
24852493 }
2486- return new JSONObject (object );
2494+ if (objectsRecord != null ) {
2495+ return new JSONObject (object , objectsRecord );
2496+ }
2497+ else {
2498+ return new JSONObject (object );
2499+ }
2500+ }
2501+ catch (JSONException exception ) {
2502+ throw exception ;
24872503 } catch (Exception exception ) {
24882504 return null ;
24892505 }
0 commit comments