Skip to content
Advertisement

Serialize Enum as String for validation using Jackson

I’m trying to validate an Enum using the custom validator, in my custom validator I’m trying to return a custom message when a parameter does not exist in the enum values.

Bellow my enum

JavaScript

Bellow my PostMapping method

JavaScript

I can’t switch the type of enum to string in the method itself because I’m using swagger which displays a nice selection list for enums.

Unfortunately, when I try to give a different value for Type, it returns a bad request and my validators are not triggered.

So I’m trying to serialize my enum to be interpreted as String when it arrives at the controller and to do that I need to use Jackson, I tried to look for a solution but I can’t find a good one for my case.

Bellow are my validators

JavaScript
JavaScript

Could anyone tell me how can I turn my enum as a string so my validator could handle it?

Advertisement

Answer

I found it, I was able to do it by implementing a new converter, which will convert string to a valid enum value or an INVALID value:

JavaScript

After that I added a new Configuration for my converter:

JavaScript

Also I had to hide the INVALID value of my enum from swagger by adding the @Schema annotation:

JavaScript

Finally in the validators, I should reject the INVALID value and display a custom message:

JavaScript

The annotation for the previous validator:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement