From 30c88b6e8fa9c720db998bb696dbad52a34dd6fd Mon Sep 17 00:00:00 2001 From: "shaojin.wensj" Date: Wed, 17 Jan 2024 23:05:57 +0800 Subject: [PATCH] JSON.toJSON support reference, for issue #2187 --- .../fastjson2/writer/ObjectWriterAdapter.java | 6 ++- .../fastjson2/issues_2100/Issue2187.java | 40 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterAdapter.java b/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterAdapter.java index 69d1bd0ba9..1ad86a64ec 100644 --- a/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterAdapter.java +++ b/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterAdapter.java @@ -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; } @@ -659,6 +660,9 @@ public JSONObject toJSONObject(T object, long features) { continue; } + if (fieldValue == object) { + fieldValue = jsonObject; + } jsonObject.put(fieldWriter.fieldName, fieldValue); } diff --git a/core/src/test/java/com/alibaba/fastjson2/issues_2100/Issue2187.java b/core/src/test/java/com/alibaba/fastjson2/issues_2100/Issue2187.java index e741d5e974..2b21f6b05c 100644 --- a/core/src/test/java/com/alibaba/fastjson2/issues_2100/Issue2187.java +++ b/core/src/test/java/com/alibaba/fastjson2/issues_2100/Issue2187.java @@ -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 @@ -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 values; + } }