Skip to content

Commit

Permalink
fix jackson annotation JsonFormat compatible, for issue #2836
Browse files Browse the repository at this point in the history
  • Loading branch information
wenshao committed Aug 8, 2024
1 parent 9728336 commit 3e0bc55
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 6 deletions.
20 changes: 14 additions & 6 deletions core/src/main/java/com/alibaba/fastjson2/util/BeanUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -693,12 +693,20 @@ public static boolean isWriteEnumAsJavaBean(Class clazz) {

Class<? extends Annotation> 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;
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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);
}
}

0 comments on commit 3e0bc55

Please sign in to comment.