jackson 枚举 enum json 解析类型 返回数字 或者自定义文字 How To Serialize Enums as JSON Objects with Jackson
1、枚举类如下
package com.irobotzz.docs.bms.constants; import com.baomidou.mybatisplus.annotation.EnumValue; import com.common.auth.constants.IBaseEnum; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonValue; import lombok.Getter; /** * 用户启用状态 * * @author Yungui.zheng * @date 2020/05/11 */ @Getter @JsonFormat(shape = JsonFormat.Shape.OBJECT) public enum StatusEnum implements IBaseEnum<Integer> { /** * 用户启用状态常量 */ DISABLED(0, "停用"), ENABLED(1, "启用"), UNKNOWN(-1,"未知"); @EnumValue private final Integer value; private final String desc; StatusEnum(Integer value, String desc) { this.value = value; this.desc = desc; } }
这种写法返回到前端时一个对象:{value:1,desc:"启用"}
2、希望返回数字value,使用注解 @JsonValue
package com.irobotzz.docs.bms.constants; import com.baomidou.mybatisplus.annotation.EnumValue; import com.common.auth.constants.IBaseEnum; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonValue; import lombok.Getter; /** * 用户启用状态 * * @author Yungui.zheng * @date 2020/05/11 */ @Getter @JsonFormat(shape = JsonFormat.Shape.OBJECT) public enum StatusEnum implements IBaseEnum<Integer> { /** * 用户启用状态常量 */ DISABLED(0, "停用"), ENABLED(1, "启用"), UNKNOWN(-1,"未知"); @EnumValue @JsonValue private final Integer value; private final String desc; StatusEnum(Integer value, String desc) { this.value = value; this.desc = desc; } }
这个时候返回值为:1