Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize enum ignoring case in Spring Boot controller

I have Spring Boot endpoint which has enum as query param:

@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?

This question is not duplicate because it's related to query param deserialization.

like image 313
Justinas Jakavonis Avatar asked May 08 '18 10:05

Justinas Jakavonis


1 Answers

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. Thanks to @Dave for pointing this out in the comments.


Spring Boot 2.0 is using Jackson 2.9 which has ACCEPT_CASE_INSENSITIVE_ENUMS feature. You should be able to enable it by setting

spring.jackson.mapper.ACCEPT_CASE_INSENSITIVE_ENUMS = true 

property as per docs, Appendix A.

like image 154
Karol Dowbecki Avatar answered Sep 20 '22 13:09

Karol Dowbecki