@JsonFormat(shape = JsonFormat.Shape.OBJECT)的作用
作用
这个注解的作用是将枚举类像对象一样序列化。
为什么使用?
如果不以这种方式,那么枚举类的值就仅仅是他的名字(枚举类自带的name字段),这样前后端协作时就不好知道你的枚举类都是什么含义,还要自己写额外的文档,一旦修改或者增加则还要修改文档,很不方便。
使用方式
定义这样一个接口,让需要以这种方式序列化的枚举类都实现这个接口即可
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public interface BaseEnum {
}
一般会这样定义接口:要求枚举类至少有个对其自身含义的解释
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public interface BaseEnum {
String desc();
}
然后枚举类的定义:
import lombok.Getter;
@Getter
public enum AnswerStatus implements BaseEnum {
//正确
CORRECT("正确"),
//错误
WRONG("错误"),
//半正确
PARTIAL("半对");
private final String name;
private final String desc;
AnswerStatus(String desc) {
this.name = this.name();
this.desc = desc;
}
@Override
public String desc() {
return this.desc;
}
}
如果写这样一个接口方法:
@GetMapping
public AnswerStatus[] getAnswerStatus() {
return AnswerStatus.values();
}
其查询结果为: