SpringBoot实现前端传入数值Controller层接收为枚举

定义枚举

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;
    }

 

成功

SpringBoot实现前端传入数值Controller层接收为枚举_第1张图片

 

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

 

你可能感兴趣的:(SpringBoot,java,spring,boot)