I am trying to build json parser using jsckson. Below is my code of enum class:
public enum Priority {
@JsonProperty("LOW")
LOW(100),
@JsonProperty("MEDIUM")
MEDIUM(200),
@JsonProperty("HIGH")
HIGH(300);
private int priority;
Priority(int i) {
this.priority = i;
}
public int getPriority() {
return priority;
}
}
Now I am expecting my parser to take only 3 inputs which are "HIGH", "LOW" and "MEDIUM". But it is taking the ordinal values also. For example: If my input is like:
{
"priority": 0
}
It is taking LOW priority instead of giving error.
How can I stop this?
Add the following Bean Config:
@Bean
public Jackson2ObjectMapperBuilderCustomizer enableFailOnNumbersForEnums() {
return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.featuresToEnable(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS);
}
This will stop Jackson from deserializing ordinals into Enum values. You can read more on available features to enable/disable here: https://github.com/FasterXML/jackson-databind/wiki/Deserialization-Features
You can also configure ObjectMapper
which worked in my case:
@Configuration
public class ObjectMapperConfiguration {
@Bean
public ObjectMapper objectMapperBean() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS, true);
return mapper;
}
}
The results are the same - Jackson no longer accepts ordinal values of an enum.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With