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.
@JsonProperty is used to mark non-standard getter/setter method to be used with respect to json property.
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.
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.
@SerializedName annotation indicates that the annotated member should be serialized to JSON with the provided name value in the annotation attribute.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With