springboot接收枚举

接收枚举值首先需要注意两个点

  1. 只有在使用@RequestBody形式接收对象数据时才可以使用
  2. 需要自定义Jackson的反序列化方法

只要使用@RequestBody接收对象就可以使用本方法,否则会接收报错.
这里没有去做源码查询,猜测应该是@RequestBody会将json字符串反序列化,当遇到指定枚举时会调取对应的反序列化函数,但是其他情况下默认是不去这么做的.

枚举示例如下

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

@Getter
public enum LevelEnum {

    city(1, "市"),
    county(2, "县"),
    firm(3, "企业");

    private final Integer code;
    private final String msg;
    LevelEnum(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }
    // 自定义反序列函数
    // JsonCreator.Mode.DELEGATING: 接收单个值,将接收的值整个传入自定义函数
    @JsonCreator(mode = JsonCreator.Mode.DELEGATING)
    public static LevelEnum get(Integer code) {
        if (code == null) {
            return null;
        }
        return Arrays.stream(values())
		.filter(num -> num.code ==code.intValue())
		.findAny().orElse(null);
    }
}
posted @ 2025-01-23 10:52  wds09  阅读(76)  评论(0)    收藏  举报