@JsonFormat序列化枚举
时间: 2023-11-10 22:02:32 浏览: 43
使用@JsonFormat注解可以在枚举类型的序列化过程中自定义输出格式。下面是一个示例:
```java
public enum Color {
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
RED("red", "#FF0000"),
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
GREEN("green", "#00FF00"),
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
BLUE("blue", "#0000FF");
private final String name;
private final String code;
Color(String name, String code) {
this.name = name;
this.code = code;
}
public String getName() {
return name;
}
public String getCode() {
return code;
}
}
```
在上面的示例中,我们使用@JsonFormat注解的shape属性来指定枚举类型的序列化方式为OBJECT,这将把枚举类型序列化为一个包含name和code属性的对象。然后,我们可以通过定义name和code属性以及相应的getter方法来控制输出的格式。