java中的Enum在@RestController(@ResponseBody) 注解下返回的表现

参考文档

枚举

public enum CouponType {


    PLATFORM("平台优惠券"), NEWCOMER("新人专享优惠券"), INVITE("邀请奖励优惠券"), DESIGNATED_USER("特定用户优惠券");

    private final String info;

    CouponType(String info) {
        this.info = info;
    }

    public String getInfo() {
        return info;
    }

    @Override
    public String toString() {
        return this.info;
    }
}

直接返回JSON

couponsType:"PLATFORM"

加注解返回键值对

  • 枚举类上加 @JsonFormat(shape = JsonFormat.Shape.OBJECT)

couponsType:

自定义序列化

public class CouponTypeSerializer extends StdSerializer {
    public CouponTypeSerializer() {
        super(CouponType.class);
    }

    public CouponTypeSerializer(Class t) {
        super(t);
    }


    @Override
    public void serialize(Object couponOperation, JsonGenerator generator, SerializerProvider serializerProvider) throws IOException {
        CouponType c = (CouponType) couponOperation;
        generator.writeStartObject();
        generator.writeFieldName("name");
        generator.writeString(c.name());
        generator.writeFieldName("info");
        generator.writeString(c.getInfo());
        generator.writeEndObject();
    }
}

  • 枚举类上加 @JsonSerialize(using = CouponTypeSerializer.class)

couponsType:

如果页面需要返回name,在定义的时候添加name字段最方便,配合@JsonFormat(shape = JsonFormat.Shape.OBJECT)

比如:

    PLATFORM("平台优惠券","PLATFORM") ...

    private final String info;
    private final String name;

    CouponType(String info,String name) {
        this.info = info;
        this.name=name;
    }

enum 持久化

enum 类型默认是是存储ORDINAL (enum的顺序:0,1,2)
为了代码健壮,建议保存String(enum的name属性)

   /**
     * 优惠券类型
     */
    @Enumerated(EnumType.STRING)
    private CouponType couponsType;
posted @ 2019-05-23 16:04  懒企鹅  阅读(3404)  评论(0编辑  收藏  举报