如何在requestparm中将多个值转换为enum?

x33g5p2x  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(425)

我有下面的枚举声明

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);
    }
}

我有一个控制器端点,其中delete请求保存 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.
mfuanj7w

mfuanj7w1#

在本教程第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());
    }
    // ...
}

相关问题