I use @JsonSerialize to convert the enum class to Integer, and the writing is successful; but each enum class must write a converted class, is there a way to write only one conversion class?
I tried to use generics to get the type of the enum class, but failed, this is not allowed
// error code
@JsonSerialize(using = StatusSerializer<StatusEnum>.class)
private Integer status;
@Data
public class ZkUser {
/**
* name
*/
private String name;
/**
* status
*/
@JsonSerialize(using = StatusSerializer.class)
private Integer status;
}
//==========================================================================================
public enum StatusEnum {
// d
ON(1),
OFF(0);
private final Integer code;
public static StatusEnum getEnumByCode(Integer code) {
for (StatusEnum s : values()) {
if (s.code.equals(code)) {
return s;
}
}
return null;
}
StatusEnum(Integer code) {
this.code = code;
}
public Integer getCode() {
return code;
}
}
//=========================================================================================
public class StatusSerializer<T> extends JsonSerializer<Integer> {
private T t;
@Override
public void serialize(Integer value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
var b = StatusEnum.getEnumByCode(value);
jsonGenerator.writeObject(b);
}
}