my Enum Values are: RED, BLUE, BROWN
Hi everyone, i have an Enum Field in my class called color
.
user posts a request and sets the color
parameter on the JSON to "color":"0"
, it will automatically convert 0
to RED
. How can i throw an exception when that happens to make sure integers are not allowed?
(Implementing Annotation: isValid()
doesn’t prevent the value from being converted)
How can i block auto conversion from Int to Enum?
I tried to implement an Annotation, but that didnt work.
1
Assuming you are using jackson, there is a configuration property to override this default behavior.
DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS
package org.example;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
enum Color {
RED,
BLUE,
GREEN
}
class Item {
private String name;
private Color color;
public Item() {
}
public Item(String name, Color color) {
this.name = name;
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
@Override
public String toString() {
return "name :" + name + " color: " + color;
}
}
public class Main {
public static void main(String[] args) {
String input = "{"name":"ant","color":0}";
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS, true);
try {
Item item = objectMapper.readValue(input, Item.class);
System.out.println(item);
} catch (JsonProcessingException e) {
System.out.println(e.getMessage());
}
}
}
You can also override this using application properties, or defining a bean.
Read here: https://www.baeldung.com/spring-boot-customize-jackson-objectmapper