Skip to content

Commit

Permalink
JSON.toJSON support reference, for issue #2187
Browse files Browse the repository at this point in the history
  • Loading branch information
wenshao committed Jan 17, 2024
1 parent fd63bee commit 30c88b6
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -649,7 +649,8 @@ public JSONObject toJSONObject(T object, long features) {
Collection collection = (Collection) fieldValue;
JSONArray array = new JSONArray(collection.size());
for (Object item : collection) {
array.add(JSON.toJSON(item));
Object itemJSON = item == object ? jsonObject : JSON.toJSON(item);
array.add(itemJSON);
}
fieldValue = array;
}
Expand All @@ -659,6 +660,9 @@ public JSONObject toJSONObject(T object, long features) {
continue;
}

if (fieldValue == object) {
fieldValue = jsonObject;
}
jsonObject.put(fieldWriter.fieldName, fieldValue);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;

public class Issue2187 {
@Test
Expand All @@ -29,4 +31,42 @@ public static class Bean {

public static class Item {
}

@Test
public void test1() throws Exception {
JSONObject object = new JSONObject();
object.put("ref", object);
assertSame(object, JSON.toJSON(object));
}

@Test
public void test2() throws Exception {
JSONArray array = new JSONArray();
array.add(array);
assertSame(array, JSON.toJSON(array));
}

@Test
public void test3() throws Exception {
Bean3 bean = new Bean3();
bean.value = bean;
JSONObject json = (JSONObject) JSON.toJSON(bean);
assertSame(json, json.get("value"));
}

public static class Bean3 {
public Bean3 value;
}

@Test
public void test4() throws Exception {
Bean4 bean = new Bean4();
bean.values = Arrays.asList(bean);
JSONObject json = (JSONObject) JSON.toJSON(bean);
assertSame(json, json.getJSONArray("values").get(0));
}

public static class Bean4 {
public List<Bean4> values;
}
}

0 comments on commit 30c88b6

Please sign in to comment.