7

So I'm looking at adding constraints to my json views.

I have class similar to this one

public class Person {
    @JsonProperty(required = true)
    @NotNull
    @Size(max = 50)
    private String name;
}

Should I keep both @JsonProperty(required = true) and @NotNull or should I remove one and why?


Just to be clear since Jackson 2.6 @JsonProperty(required = true) does throw an exception.

I'm using springfox-swagger and it looks like when I remove @JsonProperty(required = true) the field in the swagger is marked as optional which it isn't.

I'm just wondering about the best practice in this situation.

shammancer
  • 397
  • 2
  • 4
  • 8
  • I'm using springfox-swagger and it looks like when I remove `@JsonProperty(required = true)` the field in the swagger is marked as optional. – shammancer Aug 24 '17 at 18:05
  • Please let me know if my [answer](https://stackoverflow.com/a/45877203/1426227) works for you – cassiomolin Sep 01 '17 at 08:19
  • At this point I've decided to use both of them `@JsonProperty(required = true)` and `@NotNull`. I did not look into ApiModelProperty to closely mostly because `@JsonProperty` works for what I need... – shammancer Sep 01 '17 at 16:11

1 Answers1

7

When using @JsonProperty with required set to true on a field or method, Jackson won't perform any validation. See the documentation for further details.


For validation purposes, consider @NotNull from Bean Validation (a validation provider such as Hibernate Validator is required to perform the validation).

With Swagger, you also can use @ApiModelProperty and set required to true to indicate that a field is mandatory.

cassiomolin
  • 124,154
  • 35
  • 280
  • 359