0

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 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried with Google GSON and Jackson custom deserializer. What I found was that the JsonNode object coming into the custom deserializer overridden method has got the duplicates swallowed by the respective frameworks. I thought I should have full access to the underlying JSON payload in the method which is not the case. Hence custom deserialization may not work here, unless we take one step backward to access the parsing component in the framework code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.