Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you use @NotNull and @JsonProperty(required) in the same object

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.

like image 486
shammancer Avatar asked Aug 24 '17 17:08

shammancer


People also ask

What does @JsonProperty annotation do?

@JsonProperty is used to mark non-standard getter/setter method to be used with respect to json property.

Is JsonProperty needed?

You definitely don't need all those @jsonProperty . Jackson mapper can be initialized to sereliazie/deserialize according to getters or private members, you of course need only the one you are using. By default it is by getters.

How do I make a JSON property mandatory?

You can mark a property as required with the @JsonProperty(required = true) annotation, and it will throw a JsonMappingException during deserialization if the property is missing or null.

What annotation should you use to signify that an attribute should be serialized into JSON and provide a mapping from Java attribute name to JSON name if needed?

@SerializedName annotation indicates that the annotated member should be serialized to JSON with the provided name value in the annotation attribute.


1 Answers

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.

like image 97
cassiomolin Avatar answered Sep 23 '22 15:09

cassiomolin