我有一个简单的弹簧rest控制器,如下所示。
@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无效值的端点时,我返回了一个exeption:
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是否会将枚举设置为空?
我使用的是spring 4,我更喜欢使用注释而不是xml文件的配置
发布于 2016-11-16 01:49:11
您需要在枚举类http://chrisjordan.ca/post/50865405944/custom-json-serialization-for-enums-using-jackson中实现自定义JSON序列化方法
在枚举中使用@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;
}
https://stackoverflow.com/questions/40628523
复制相似问题