Skip to content

Commit e40a224

Browse files
committed
support user-defined enum ObjectWriter, for issue #851
1 parent 3549f15 commit e40a224

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterCreator.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -779,6 +779,11 @@ public <T> FieldWriter<T> createFieldWriter(
779779
if (objectWriter != ObjectWriterImplBigDecimal.INSTANCE) {
780780
initObjectWriter = objectWriter;
781781
}
782+
} else if (Enum.class.isAssignableFrom(fieldClass)) {
783+
ObjectWriter objectWriter = provider.cache.get(fieldClass);
784+
if (!(objectWriter instanceof ObjectWriterImplEnum)) {
785+
initObjectWriter = objectWriter;
786+
}
782787
}
783788
}
784789

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package com.alibaba.fastjson2.issues;
2+
3+
import com.alibaba.fastjson2.JSON;
4+
import com.alibaba.fastjson2.JSONWriter;
5+
import com.alibaba.fastjson2.writer.ObjectWriter;
6+
import lombok.*;
7+
import org.junit.jupiter.api.Test;
8+
9+
import java.lang.reflect.Type;
10+
11+
import static org.junit.jupiter.api.Assertions.assertEquals;
12+
13+
public class Issue851 {
14+
@Test
15+
public void testUser() {
16+
JSON.register(UserType.class, new ObjectWriter<UserType>() {
17+
@Override
18+
public void write(JSONWriter jsonWriter, Object object, Object fieldName, Type fieldType, long features) {
19+
jsonWriter.writeInt32(((UserType) object).getValue());
20+
}
21+
});
22+
23+
User user = new User();
24+
user.setName("张三");
25+
user.setUserType(UserType.BOY);
26+
user.setAge(20);
27+
28+
assertEquals("{\"age\":20,\"name\":\"张三\",\"userType\":1}", JSON.toJSONString(user));
29+
}
30+
31+
@RequiredArgsConstructor
32+
@Getter
33+
public enum UserType implements FierceEnum {
34+
BOY(1, "男孩"),
35+
GIRL(2, "女孩");
36+
private final Integer value;
37+
private final String name;
38+
}
39+
40+
@Data
41+
public static class User {
42+
private String name;
43+
private Integer age;
44+
private UserType userType;
45+
}
46+
47+
public interface FierceEnum {
48+
/**
49+
* 获取枚举值名称
50+
*
51+
* @return 名称
52+
*/
53+
String getName();
54+
55+
Integer getValue();
56+
57+
/**
58+
* 获取枚举值描述
59+
*
60+
* @return 描述
61+
*/
62+
default String getDescription() {
63+
return null;
64+
}
65+
66+
static <T> T getEnum(final Class<T> clazz, final Integer value) {
67+
if (clazz.isEnum() && FierceEnum.class.isAssignableFrom(clazz)) {
68+
final T[] constants = clazz.getEnumConstants();
69+
for (T constant : constants) {
70+
final FierceEnum item = (FierceEnum) constant;
71+
if (item.getValue().equals(value)) {
72+
return constant;
73+
}
74+
}
75+
}
76+
// 找不到或者不是枚举类,则返回null
77+
return null;
78+
}
79+
}
80+
}

0 commit comments

Comments
 (0)