From 029306189d1557a8bb0e9e7488f35dd3d21efd95 Mon Sep 17 00:00:00 2001 From: yanxutao89 <910135896@qq.com> Date: Thu, 28 Nov 2024 09:05:28 +0800 Subject: [PATCH] Fix 2981 (#3184) * fix inconsistent behaviour when enable WriteClasName, for issue #2981 * fix checkstyle --- .../main/java/com/alibaba/fastjson2/JSON.java | 4 ++- .../fastjson2/issues_2900/Issue2981.java | 28 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 core/src/test/java/com/alibaba/fastjson2/issues_2900/Issue2981.java diff --git a/core/src/main/java/com/alibaba/fastjson2/JSON.java b/core/src/main/java/com/alibaba/fastjson2/JSON.java index 4b0a2269ec..838ec728b9 100644 --- a/core/src/main/java/com/alibaba/fastjson2/JSON.java +++ b/core/src/main/java/com/alibaba/fastjson2/JSON.java @@ -3859,7 +3859,9 @@ static Object toJSON(Object object, JSONWriter.Feature... features) { JSONFactory.createWriteContext() : JSONFactory.createWriteContext(features); Class valueClass = object.getClass(); ObjectWriter objectWriter = writeContext.getObjectWriter(valueClass, valueClass); - if (objectWriter instanceof ObjectWriterAdapter && !writeContext.isEnabled(JSONWriter.Feature.ReferenceDetection)) { + if (objectWriter instanceof ObjectWriterAdapter + && !writeContext.isEnabled(JSONWriter.Feature.ReferenceDetection) + && (objectWriter.getFeatures() & JSONWriter.Feature.WriteClassName.mask) == 0) { ObjectWriterAdapter objectWriterAdapter = (ObjectWriterAdapter) objectWriter; return objectWriterAdapter.toJSONObject(object, writeContext.features); } diff --git a/core/src/test/java/com/alibaba/fastjson2/issues_2900/Issue2981.java b/core/src/test/java/com/alibaba/fastjson2/issues_2900/Issue2981.java new file mode 100644 index 0000000000..3bd84ceb89 --- /dev/null +++ b/core/src/test/java/com/alibaba/fastjson2/issues_2900/Issue2981.java @@ -0,0 +1,28 @@ +package com.alibaba.fastjson2.issues_2900; + +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONWriter; +import com.alibaba.fastjson2.annotation.JSONType; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class Issue2981 { + @Test + public void test() { + Shape.Circle circle = new Shape.Circle(); + circle.setRadius(5); + assertEquals(JSON.parse(JSON.toJSONString(circle)), JSON.toJSON(circle)); + } + + @JSONType(typeKey = "type", seeAlso = Shape.Circle.class) + public static class Shape { + @JSONType(typeKey = "type", typeName = "circle", serializeFeatures = JSONWriter.Feature.WriteClassName) + public static class Circle + extends Shape { + private int radius; + public int getRadius() { return radius; } + public void setRadius(int radius) { this.radius = radius; } + } + } +}