|
| 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