枚举类的多个属性在入参的时候根据其中指定的属性进行格式化

发布时间 2023-09-28 11:11:14作者: 鸭猪是的念来过倒

1:需求描述

一个枚举类有code和desc两个属性,页面只需要传递code数字,内部直接转换成对应的枚举

 

2:实现

通过@JsonCreator来序列化入参,就是把前端传过来的code转换成枚举

通过@JsonValue该字段,返回数据时则把枚举转换成code

2.1:创建枚举

package com.boot.model;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;

/**
 * @author test
 */

public enum UserType {
    A(1, "老大"),
    B(2, "老二"),
    C(3, "老三");
    private Integer code;
    private String desc;

    UserType(Integer code, String desc) {
        this.code = code;
        this.desc = desc;
    }

    @JsonValue
    public Integer getCode() {
        return code;
    }

    public String getDesc() {
        return desc;
    }

    /**
     * 入参时,前端传入的code会在这里转换成对应的枚举
     */
    @JsonCreator
    public static UserType getUserTypeByCode(Integer code) {
        UserType[] values = values();
        for (UserType v : values) {
            if (v.getCode().equals(code)) {
                return v;
            }
        }
        throw new NullPointerException("没有找到对应的枚举");
    }
}

 

2.2:创建传输对象

package com.boot.model;

import lombok.Data;

/**
 * @author test
 */
@Data
public class EnumModel {
    private String id;
    private String name;
    private String desc;

    private UserType userType;

}

2.3:创建controller

package com.boot.test;

import com.boot.model.EnumModel;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author test
 */
@RestController
@RequestMapping("/enum")
public class EnumController {

    @PostMapping
    public EnumModel getEnum(@RequestBody EnumModel model) {
        System.out.println(model);
        return model;
    }
}

3:测试

 userType分别传了1,2,3请求。后台打印