2

Let's say i have such json and i would like to deserialize it to an object called SubscriberProfile.

{ "field1": "value1", "field2": "value2", "field3": "value3" }

When i use following code it works without any problem,

objectMapper.readValue(json,SubscriberProfile.class);

but i want objectmapper throw and exception if field2 is missing in json (field1 and field2 can be missing).

so such json should throw an exception

{ "field1": "value1", "field3": "value3" }

I've tried to use @JsonProperty(required=true) annotation but works only when serialize it.

Do you have any idea how can i solve this problem?

Thanks in advance

Altan Gokcek
  • 91
  • 2
  • 9
  • In short; jackson doesn't validate on deserialization - you'll need to validate the object post deserialization, eg using hibernate-validator (the reference implementation of JSR-303) – beresfordt Mar 14 '16 at 12:32

1 Answers1

4

You need to remove the default constructor for your bean class. It's what allows Jackson to create a bean without your required field. For example (modified from here):

public class NonDefaultBean {
    private final String myRequired;
    private String myNotRequired;

    @JsonCreator
    public NonDefaultBean(@JsonProperty("myRequired") String myRequired) {
        this.myRequired = myRequired;
    }

    public void setMyNotRequired(String myNotRequired) {
        this.myNotRequired = myNotRequired;
    }
}
Dunes
  • 37,291
  • 7
  • 81
  • 97
  • I would have expected `required=false` on the `@JsonProperty` to have the same effect but it doesn't. – malana Oct 03 '18 at 21:48