之前其实已经做了序列化了,因为用了mp,我所有枚举类型字段都做了序列化,但是序列化结果就是枚举字段的描述
import com.baomidou.mybatisplus.annotation.EnumValue;
import com.fasterxml.jackson.annotation.JsonValue;
import com.ruoyi.framework.config.BaseEnum;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum ChargeType implements BaseEnum{
WEIXIN(0,"微信"),ZHIFUBAO(1,"支付宝"),BANKTRANS(2,"银行转账") ;
@EnumValue private Integer v;
@JsonValue private String status;
}
BaseEnum就是个接口,一个是getV,一个是getStatus,至于说为什么要写接口,因为反序列化时方便,这里不赘述.
现在我想在前端,既显示枚举值,又显示枚举描述,只需字段加上@JsonSerialize(using=MyEnumSerializer.class)
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.ruoyi.framework.config.BaseEnum;
public class MyEnumSerializer extends JsonSerializer<Enum> {
@Override
public void serialize(Enum value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeNumberField("code",((BaseEnum)value).getV());
gen.writeStringField("status",((BaseEnum)value).getStatus());
gen.writeEndObject();
}
}