Java validator for String

爷,独闯天下 提交于 2019-12-25 07:47:09

问题


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?

Let's say I have the following:

class Person {
String name;
int age;
}

I am binding JSON to Person.

The JSON payload looks like the following:

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

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

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

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

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.

Thanks for your time!


回答1:


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.

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.



来源:https://stackoverflow.com/questions/14917104/java-validator-for-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!