java 使用约束注释验证 json 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27063892/
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
validating json using constraints annotations is not working
提问by igx
I am trying to validate a json when deserialize it using constraints annotations but it doesn't seem to work. for example
我试图在使用约束注释反序列化 json 时验证它,但它似乎不起作用。例如
import com.fasterxml.Hymanson.annotation.JsonProperty;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
public class SimpleFooRequest {
@NotNull
@JsonProperty(value = "count")
@Min(value = 100,message = "must be min 10")
private Integer count;
@NotNull
private String name;
public String getName() {return name; }
public void setName(String name) { this.name = name; }
public Integer getCount() {return count;}
public void setCount(Integer count) {this.count = count;}
}
when trying to unmarshal the json
尝试解组 json 时
@Test
public void testFooRequest() throws Exception
{
String fooJson = {"count":-10}
ObjectMapper mapper = new ObjectMapper()
SimpleFooRequest request = mapper.readValue(fooJson,SimpleFooRequest.class);
assert request.getCount().equals(-10);//expected fail but it pass !!!
}
it seems to pass although I expected that the assertion will fail due to the count min value limitation . I also tried to put the annotations on the setters but got same results
虽然我预计断言会因计数最小值限制而失败,但它似乎通过了。我也尝试将注释放在 setter 上,但得到了相同的结果
I have <mvc:annotation-driven />
and hibernate-validator-4.3.1.Final.jar
in my dependencies
I know that I can create custom validator but I thought that for simple validations I can use the annotations .
what do I need to do to make it work ?
我有<mvc:annotation-driven />
并且hibernate-validator-4.3.1.Final.jar
在我的依赖项中我知道我可以创建自定义验证器但我认为对于简单的验证我可以使用 annotations 。我需要做什么才能使它工作?
回答by Paul Samsotha
Annotations are just meta-data. They're not programs that can perform any validation. The validator is the program that will make use of the meta-data. In a container, the container will manage the validator. In basic unit tests or standalones, you will need to manage the validator yourself.
注释只是元数据。它们不是可以执行任何验证的程序。验证器是将使用元数据的程序。在容器中,容器将管理验证器。在基本单元测试或独立测试中,您需要自己管理验证器。
That being said, even a validator cannot stop the object from being created/populated (as you seem to be asserting in your test). It just validates that the value is valid. If not, the validator throws an exception and/or lists some constraint violations. Either the container, or you should handle what to do with the exceptions/violations.
话虽如此,即使是验证器也无法阻止对象的创建/填充(正如您在测试中所断言的那样)。它只是验证该值是否有效。如果没有,验证器会抛出异常和/或列出一些违反约束的行为。容器,或者您应该处理如何处理异常/违规。
And AFAIK, there's no ObjectMapper
configuration for automatic JSR-303 support while deserializing
和 AFAIK,ObjectMapper
反序列化时没有自动 JSR-303 支持的配置
A better unit test, might look something like
更好的单元测试,可能看起来像
/* ----- Using the Hibernate Validator implementation ----- */
@Test
public void testInvalidCount() throws Exception {
final String json = "{\"count\":-10, \"name\":\"Stack\"}";
ObjectMapper mapper = new ObjectMapper();
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
SimpleFooRequest request = mapper.readValue(
json, SimpleFooRequest.class);
Set<ConstraintViolation<SimpleFooRequest>> violations
= validator.validate(request);
Assert.assertEquals(1, violations.size());
Assert.assertEquals("must be min 10",
violations.iterator().next().getMessage());
}
- See Getting started with Hibernate Validatorfor some more examples
- 有关更多示例,请参阅Hibernate Validator 入门
回答by user3027497
How about validating at the setter method? Hymanson calls your setters if exists...
如何在 setter 方法中进行验证?如果存在,Hyman逊会调用你的二传手......