我有一个简单的 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
,对于null
或undefined
值,只需返回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/