Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson deserialization convertValue should fail on nulls

Hy,

What I have:

  1. A map with current values

    { "name": "Cedrik", "surname": "MySurname", }

  2. A public class myPojo

    @JsonProperty(required = true) private String name;
    @JsonProperty(required = true) private String surname;
    @JsonProperty(required = true) private String age;
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public String getSurname() {
        return surname;
    }
    
    public void setSurname(String surname) {
        this.surname = surname;
    }
    
    public String getAge() {
        return age;
    }
    
    public void setAge(String age) {
        this.age = age;
    }
    

What I want is to make the conversion from Map to POJO to fail(throw an exception) if one field from the map is not fulfilling the POJO.

It doesn't seem to work with any kind of configuration using DeserializationFeature. I tried to tweak all configs that have something to do with null fields

example:

objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, false)
objectMapper.configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, true);

This should throw an exception but it doesn't:

MyPojo myPojo = MAPPER.convertValue(action.getParams(), MyPojo.class);

Any idea on how I make it to throw an exception during conversion if the age field is missing from the map and required by POJO?

like image 688
Cedrik Avatar asked Dec 14 '25 07:12

Cedrik


1 Answers

Jackson does not support validation (it's explicitly out of scope), so you need to validate separately after deserialization, for example by using Bean Validation implementation (like Hibernate Validator).

like image 115
StaxMan Avatar answered Dec 15 '25 21:12

StaxMan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!