java 你是否应该在同一个对象中使用 @NotNull 和 @JsonProperty(required)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45867473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:56:52  来源:igfitidea点击:

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

javajsonspringvalidationHymanson

提问by shammancer

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

所以我正在考虑向我的 json 视图添加约束。

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 @NotNullor should I remove one and why?

我应该保持双方@JsonProperty(required = true)@NotNull或者我应该删除一个,为什么?



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

只是要清楚,因为 Hymanson 2.6@JsonProperty(required = true)确实抛出了异常

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.

我正在使用 springfox-swagger,看起来当我删除@JsonProperty(required = true)swagger中的字段时,它被标记为可选,而事实并非如此。

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

我只是想知道在这种情况下的最佳实践。

采纳答案by cassiomolin

When using @JsonPropertywith requiredset to trueon a field or method, Hymanson won't perform any validation. See the documentationfor further details.

在字段或方法上使用@JsonPropertywith requiredset totrue时,Hymanson 不会执行任何验证。有关更多详细信息,请参阅文档



For validation purposes, consider @NotNullfrom Bean Validation (a validation provider such as Hibernate Validatoris required to perform the validation).

出于验证目的,请考虑@NotNull从 Bean 验证(需要使用Hibernate Validator等验证提供程序来执行验证)。

With Swagger, you also can use @ApiModelPropertyand set requiredto trueto indicate that a field is mandatory.

使用 Swagger,您还可以使用@ApiModelProperty和设置requiredtrue来指示某个字段是必填字段。