'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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source