javajsonjacksondeserializationprimitive-types

How can I make jackson throwing error when a value for primitive is not set in json?


Given the code:

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        System.out.println(new ObjectMapper().readValue("{}", Foo.class));
    }

    public static class Foo {
        long id;

        public long getId() { return id; }
        public void setId(long id) { this.id = id; }

        @Override
        public String toString() { return "For(id=" + id + ')'; }
    }
}

I want exception thrown instead of 0 in the id field. I tried different things like @JsonProperty(required = true), @JsonInclude(JsonInclude.Include.NON_DEFAULT) but it does not work and still just silently sets 0

How do I force it to throw an exception when there is no value for the field or it is set to null in JSON?


Solution

  • To my knowlendge that's only supported when using contructors. Feature that controls it is DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES. You need to annotate the constructor, which jackson will use with @JsonCreator, and arguments in the constructor with @JsonProperty. Like this:

    public class Foo {
    
        long id;
    
        @JsonCreator
        public Foo(@JsonProperty("id") long id) {
            this.id = id;
        }
    
        //getters and setters
    
        @Override
        public String toString() {
            return "For(id=" + id + ')';
        }
    }
    

    And enable the feature for the mapper.

    public class Main {
    
        public static void main(String[] args) throws IOException {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, true);
            System.out.println(mapper.readValue("{}", Foo.class));
        }
    }
    

    Edit: That's only for properties missing from content. If you need to specifically fail null properties(not applicable for you case, since you use primitives, but adding for completeness), you need this feature DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES. You can enable it the same way as the other property in the example.