Skip to content

Commit

Permalink
Fix 2981 (#3184)
Browse files Browse the repository at this point in the history
* fix inconsistent behaviour when enable WriteClasName, for issue #2981

* fix checkstyle
  • Loading branch information
yanxutao89 authored Nov 28, 2024
1 parent d65ca79 commit 0293061
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
4 changes: 3 additions & 1 deletion core/src/main/java/com/alibaba/fastjson2/JSON.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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; }
}
}
}

0 comments on commit 0293061

Please sign in to comment.