字符串的Java验证器 [英] Java validator for String

查看:99
本文介绍了字符串的Java验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Hibernate验证程序验证在绑定到带有验证程序注释的Java类的JSON有效负载中多次出现的元素?

How do I validate using Hibernate validator for elements appearing more than once in a JSON payload bound to a Java class annotated with validator annotations?

假设我有以下内容:

class Person {
String name;
int age;
}

我将JSON绑定到Person.

I am binding JSON to Person.

JSON有效负载如下所示:

The JSON payload looks like the following:

{
 "name":"someName",
  "age":30
}

比方说,有效载荷具有2个名称"字段,如下所示重复.

Let's say the payload has 2 "name" fields repeated as below.

 {
     "name":"someName",
     "name" : "otherName",
      "age":30
 }

然后,我想使用验证器对此进行验证.如果我使用@Size(min = 1,max = 1),它将适用于Collection对象.

Then I like to use the validator to validate this. It will work for Collection objects if I use @Size(min=1, max=1).

我想知道如何使它适用于String.使用String @Size会尝试查找字符串内容的长度,而不是有效内容中字符串内容的次数.

I am wondering how I make this work for String. With String @Size tries to look for the length of the string content and not the number of times the string content in the payload.

感谢您的时间!

推荐答案

这是不可能的. JSON反序列化和Bean验证完全是两个 .到您的Hibernate验证生效时,它会看到一个带有单个名称字段的Person对象.

This is not possible. JSON deserialization and Bean validation are two entirely different things. By the time your Hibernate validation kicks in all it sees is a Person object, with a single name field.

JSON库的行为将确定哪些名称"字段将反序列化到Java bean中(或者是否引发异常).在大多数情况下,如果要验证是否没有重复项,则需要编写一些自定义反序列化代码.

It is the behavior of your JSON library that will determine which of the "name" fields will be deserialized into the Java bean (or if an exception will be thrown). For the most part, if you want to validate that no duplicates are supplied then you are going to need to write some custom deserialization code.

这篇关于字符串的Java验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆