定义枚举

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Getter;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 *
 * @auther: lkz
 * @date: 2021/04/03
 * @version: 1.0
 * @description:
 */
@Getter
// 让枚举返回的时候携带里面的值
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum NumEnum {

    M_0(0, "0的枚举"),
    M_1(1, "1的枚举"),
    M_2(2, "2的枚举"),
    UNKNOWN(-1, "未知");

    private Integer code;

    private String msg;

    private NumEnum(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    // 自定义反序列函数
    // JsonCreator.Mode.DELEGATING: 接收单个值,将接收的值整个传入自定义函数
    @JsonCreator(mode = JsonCreator.Mode.DELEGATING)
    public static NumEnum get(Integer code) {
        if (code == null) return UNKNOWN;
        return Arrays.stream(NumEnum.values()).filter(i -> i.getCode() == code.intValue()).findAny().orElse(UNKNOWN);

    }
}

 

实体类

public class Test implements Serializable {

    private static final long serialVersionUID = 1L;
    
    private int id;
    
    private NumEnum num;
}

接口

@PostMapping("/test")
    public Object save(@RequestBody Test test) {

        return test;
    }

 

成功

 

Demo:https://gitee.com/awfaef/jpaenumdemo.git

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐