diff --git a/core/src/main/java/com/alibaba/fastjson2/util/BeanUtils.java b/core/src/main/java/com/alibaba/fastjson2/util/BeanUtils.java index af7eb4fbdd..0abb287a28 100644 --- a/core/src/main/java/com/alibaba/fastjson2/util/BeanUtils.java +++ b/core/src/main/java/com/alibaba/fastjson2/util/BeanUtils.java @@ -693,12 +693,20 @@ public static boolean isWriteEnumAsJavaBean(Class clazz) { Class annotationType = annotation.annotationType(); String name = annotationType.getName(); - if ("com.alibaba.fastjson.annotation.JSONType".equals(name)) { - BeanInfo beanInfo = new BeanInfo(JSONFactory.getDefaultObjectWriterProvider()); - BeanUtils.annotationMethods(annotationType, method -> BeanUtils.processJSONType1x(beanInfo, annotation, method)); - if (beanInfo.writeEnumAsJavaBean) { - return true; - } + BeanInfo beanInfo = new BeanInfo(JSONFactory.getDefaultObjectWriterProvider()); + switch (name) { + case "com.alibaba.fastjson.annotation.JSONType": + BeanUtils.annotationMethods(annotationType, method -> BeanUtils.processJSONType1x(beanInfo, annotation, method)); + break; + case "com.fasterxml.jackson.annotation.JsonFormat": + boolean useJacksonAnnotation = JSONFactory.isUseJacksonAnnotation(); + if (useJacksonAnnotation) { + processJacksonJsonFormat(beanInfo, annotation); + } + break; + } + if (beanInfo.writeEnumAsJavaBean) { + return true; } } diff --git a/core/src/test/java/com/alibaba/fastjson2/issues_2800/Issue2836.java b/core/src/test/java/com/alibaba/fastjson2/issues_2800/Issue2836.java new file mode 100644 index 0000000000..4820699be0 --- /dev/null +++ b/core/src/test/java/com/alibaba/fastjson2/issues_2800/Issue2836.java @@ -0,0 +1,53 @@ +package com.alibaba.fastjson2.issues_2800; + +import com.alibaba.fastjson2.JSON; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.Getter; +import org.junit.jupiter.api.Test; + +import java.io.Serializable; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class Issue2836 { + @Getter + @JsonFormat(shape = JsonFormat.Shape.OBJECT) + public enum Type + implements Serializable { + A("1", "1"), + B("2", "2"), + C("3", "3"); + private final String code; + private final String msg; + + Type(String code, String msg) { + this.code = code; + this.msg = msg; + } + } + + @AllArgsConstructor + @Data + public static class User + implements Serializable { + private String name; + private Type type; + } + + @Test + public void test() throws Exception { + ObjectMapper objectMapper = new ObjectMapper(); + + User user = new User("test", Type.B); + String test = JSON.toJSONString(user); + String jacksonResult = objectMapper.writeValueAsString(user); + assertEquals(jacksonResult, test); + String jsonString = JSON.toJSONString(Type.A); + assertEquals( + objectMapper.writeValueAsString(Type.A), + jsonString); + } +}