java - Spring Controller 枚举请求验证

标签 java spring spring-mvc

我有一个简单的 Spring 支架 Controller ,如下所示。

@RestController
public class MyController {

@RequestMapping(path = "mapping", method = RequestMethod.POST, produces = {"application/json"})
    public MyResponse create(@RequestBody MyModel requestParam
    ) throws InvalidApplicationSentException, AuthenticationFailedException {
 // method body
}

这是用作请求参数的 MyModel 类。

public class MyModel {
    private RequestType requestType;
    // a lot of other properties ..
}

现在,当我尝试调用此端点并为 RequestType 传递无效值时,我收到一个异常:

org.springframework.http.converter.HttpMessageNotReadableException
Could not read document: Can not construct instance of com.mypackage.RequestType from String value 'UNDEFINED': value not one of declared Enum instance names: [IMPROTANT, NOT_IMPORTANT]

有没有办法让 spring 在传递错误值时将枚举设置为 null 并且不抛出错误?

我使用的是 spring 4,我更喜欢使用注释而不是 xml 文件进行配置

最佳答案

您需要在枚举类中实现自定义 JSON 序列化方法 http://chrisjordan.ca/post/50865405944/custom-json-serialization-for-enums-using-jackson

在枚举中使用@JsonCreator,对于nullundefined值,只需返回null即可开始。

@JsonCreator
public static RequestType create(String value) {
    if(value == null) {
        return null;
    }
    for(RequestType v : values()) {
        if(value.equals(v.getName())) {
            return v;
        }
    }
    return null;
}

关于java - Spring Controller 枚举请求验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40628523/

相关文章:

java - bufferedReader.readline 返回 null

java - 从 angularJs 调用 java Controller

java - 如何在 httpclient 4.3+ 中更新 HttpClient 的设置?

java - 使用 tomcat7 部署应用程序的问题

java - 如何使用 Spring Boot 从文件中获取数据列表?

java - 如何在不使用 return 和 System.exit() 的情况下退出我的程序?

java - Jersey 休息客户端不添加查询参数

spring - @ControllerAdvice 异常处理方法不会被调用

spring-mvc - 在spring mvc中调用同一 Controller 的另一个方法内的同一 Controller 的方法

mysql - com.mysql.jdbc.MysqlDataTruncation : Data truncation: Incorrect datetime value