Enum 在 jackson 序列化和反序列化時默認使用枚舉的name(), 而一般存儲的數據可能是自定義字段。可以通過一下方法改進。
- 通過@JsonValue指定序列化的字段為code
- 通過@JsonCreator 指定反序列化構造函數
- 構造靜態Map提高查詢效率,而不是每次都去循環values()查詢
public enum UserAgentEnum {
IOS(1, "IOS"),
ANDROID(2, "ANDROID"),
WXSP(3, "微信小程序"),
PC(4, "PC"),
H5(5, "H5");
@JsonValue
@Getter
private final int code;
@Getter
private final String description;
UserAgentEnum(int code, String description) {
this.code = code;
this.description = description;
}
private static final Map<Integer, UserAgentEnum> VALUES = new HashMap<>();
static {
for (final UserAgentEnum userAgent : UserAgentEnum.values()) {
UserAgentEnum.VALUES.put(userAgent.getCode(), userAgent);
}
}
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static UserAgentEnum of(int code) {
return UserAgentEnum.VALUES.get(code);
}
}