gpt4 book ai didi

java - Spring Controller 枚举请求验证

转载 作者:行者123 更新时间:2023-11-30 07:02:38 24 4
gpt4 key购买 nike

我有一个简单的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com