一、背景
在开发的时候我们经常会将对应的类型、状态等可枚举的值通过java枚举来管理。
以往的经验都是在Entity实体类上面使用int或者 short等基本数据类型来管理,然后在注释上面加上对应的枚举来关联。
但能不能直接使用 枚举类 来代替 int或者 short呢?
二、Jackson序列化和反序列化注解
jackson在序列化对应的时候会将类上面所有的 getter方法生成对应的json属性。
反序列化的时候会将类上的 setter 方法和json属性关联生成java对象。
Enum枚举类型除外。
反序列化
enum Type {
a(1, "a"),
b(2, "b"),
;
private final int value;
private final String describe;
Type(int value, String describe) {
this.value = value;
this.describe = describe;
}
@JsonValue
public int getValue() {
return value;
}
public String getDescribe() {
return describe;
}
@JsonCreator
public static Type fromValue(int value) {
for (Type anEnum : Type.values()) {
if (Objects.equals(anEnum.getValue(), value)) {
return anEnum;
}
}
return null;
}
}
如上,我们要将json 字符串中的 Number类型的值直接序列化生成枚举,可以使用 @JsonCreator注解实现。
实验:
@Test
public void t11() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Type type = objectMapper.readValue("1", Type.class);
System.out.println(type);
}
//==========
type is: a
序列化
如果直接将枚举json序列化,默认会将枚举的名字当做json的value。
需求是要将枚举中的属性value进行序列化。
可以使用 @JsonValue这个注解定义了整个对应的序列化方法,jackson会将这个方法的输出作为序列化的输出。
实验:
@Test
public void t12() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
String value = objectMapper.writeValueAsString(Type.a);
System.out.println("Type serialize value:" + value);
}
//============
Type serialize value:1