简体   繁体   English

在 Spring Boot 控制器中反序列化枚举忽略大小写

[英]Deserialize enum ignoring case in Spring Boot controller

I have Spring Boot endpoint which has enum as query param:我有 Spring Boot 端点,它以枚举作为查询参数:

@GetMapping("/example")
public List<Example> getByEnum(@RequestParam(name = "exampleEnum", required = false) ExampleEnum exampleEnum) {
    // code
}

And enum class:和枚举类:

public enum ExampleEnum {
    FIRST,
    SECOND,
}

If I pass uppercase enum value to the endpoit, it deserializes well but it throws error for lowercase:如果我将大写枚举值传递给端点,它可以很好地反序列化,但会抛出小写错误:

java.lang.IllegalArgumentException: No enum constant 

How to deserialize enum ignoring case in Spring Boot Rest endpoint?如何反序列化 Spring Boot Rest 端点中忽略大小写的枚举?

This question is not duplicate because it's related to query param deserialization.这个问题不重复,因为它与查询参数反序列化有关。

EDIT: The answer below is incorrect.编辑:下面的答案是不正确的。 You have to define a custom PropertyEditor and register it with Spring @InitBinder which I explained in this post .您必须定义一个自定义PropertyEditor并将其注册到 Spring @InitBinder ,我在这篇文章中对此进行了解释。 Thanks to @Dave for pointing this out in the comments.感谢@Dave 在评论中指出这一点。


Spring Boot 2.0 is using Jackson 2.9 which has ACCEPT_CASE_INSENSITIVE_ENUMS feature. Spring Boot 2.0 使用 Jackson 2.9,它具有ACCEPT_CASE_INSENSITIVE_ENUMS功能。 You should be able to enable it by setting您应该能够通过设置启用它

spring.jackson.mapper.ACCEPT_CASE_INSENSITIVE_ENUMS = true 

property as per docs, Appendix A .根据文档,附录 A 的属性。

import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Arrays;
import java.util.Optional;

public enum ExampleEnum {
    FIRST,
    SECOND;

    @JsonCreator
    public static ExampleEnum setValue(String key) {
        return Arrays.stream(ExampleEnum.values())
            .filter(exampleEnum -> exampleEnum.toString().equals(key.toUpperCase()))
            .findAny()
            .orElse(null);
}

You can make generic converter for all enums您可以为所有枚举制作通用转换器

package ru.grancall.kb.logging.service.dto.converter;

import lombok.AllArgsConstructor;
import org.apache.commons.lang3.EnumUtils;
import java.beans.PropertyEditorSupport;

@AllArgsConstructor
public class EnumConverter extends PropertyEditorSupport {
    private Class type;

    public void setAsText(String text) {
        setValue(EnumUtils.getEnum(type, text.toUpperCase()));
    }
}

And then in any of your Controllers use it:然后在您的任何控制器中使用它:

@InitBinder
    public void initBinder(WebDataBinder dataBinder) {
        dataBinder.registerCustomEditor(YourEnum.class, new EnumConverter(YourEnum.class));
    }

If you want to get ALL your enums handled case-insensitively you can use Spring's ApplicationConversionService .如果你想让你的所有枚举都以不区分大小写的方式处理,你可以使用 Spring 的ApplicationConversionService

You only have to register it with the following little Configuration (see baeldung ):您只需使用以下小配置注册它(请参阅baeldung ):

@Configuration
public class EnumMappingConfig implements WebMvcConfigurer {
    @Override
    public void addFormatters(FormatterRegistry registry) {
        ApplicationConversionService.configure(registry);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM