gpt4 book ai didi

java - 如何在 RequestParm 中将多个值转换为枚举?

转载 作者:行者123 更新时间:2023-12-04 03:29:00 24 4
gpt4 key购买 nike

我在下面有这个枚举声明

public enum FamilyType {
FIRSTNAME("firstname"),
LASTNAME("lastname");

private final String type;

FamilyType(String type) {
this.type = type;
}

public static FamilyType fromString(String type) {
for (FamilyType t : FamilyType.values()) {
if (t.type.equals(type)) {
return t;
}
}
return converter(type);
}

@Deprecated
private static FamilyType converter(String value) {
if ("NICKNAME".equalsIgnoreCase(value)) {
return FIRSTNAME;
}
if ("SURENAME".equalsIgnoreCase(value)) {
return LASTNAME;
}

throw new InvalidFileNameException("my-enum", value);
}
}

我有一个 Controller 端点,其中删除请求将 FamilyType 保存为 Requestparam,如下所示

public String deleteFamilyType(@PathVariable String userId, @Valid @RequestParam FamilyType familyType) {

从 postman familytype=firstname 发送时,它有效,但如果发送 familytype=nickname 然后我的转换器返回

org.springframework.web.method.annotation.MethodArgumentTypeMismatchException:
Failed to convert value of type 'java.lang.String' to required type 'FamilyType';
nested exception is java.lang.IllegalArgumentException:
No enum constant FamilyType.NICKNAME
at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:133)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.

最佳答案

正在关注 this tutorial section 3 ,我们可以使用自定义转换器来覆盖默认转换Enum#valueOf

public class StringToFamilyTypeConverter implements Converter<String, FamilyType> {
@Override
public FamilyType convert(String source) {
if ("NICKNAME".equalsIgnoreCase(source)) {
return FamilyType.FIRSTNAME;
}
if ("SURENAME".equalsIgnoreCase(source)) {
return FamilyType.LASTNAME;
}
return FamilyType.valueOf(source.toUpperCase());
}
}

然后将转换器添加到MVC配置中

@Configuration
public class AppConfig implements WebMvcConfigurer {
// ...
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new StringToFamilyTypeConverter());
}
// ...
}

关于java - 如何在 RequestParm 中将多个值转换为枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67210546/

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