Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop accepting ordinal values of enum in json parsing using jackson

Tags:

java

jackson

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?

like image 538
Sutirtha Kayal Avatar asked Oct 19 '25 15:10

Sutirtha Kayal


2 Answers

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

like image 86
sechanakira Avatar answered Oct 21 '25 03:10

sechanakira


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.

like image 20
Fenio Avatar answered Oct 21 '25 04:10

Fenio