How do I validate the JSON request in Spring Boot?

Rishabh Bansal :

I want to validate the JSON request which I am receiving from the client side. I have tried using the annotations (@notnull, @length(min=1,max=8), etc., etc.) and it is working fine but the problem is that I am not able to get the fields and messages which will be getting invoked if they are invalid. Although, I am getting an error message in my Console.

List of constraint violations:

[
  ConstraintViolationImpl
  {
    interpolatedMessage=
    'must be greater than or equal to 900000000',
    propertyPath=phoneNumber,
    rootBeanClass=class
    com.org.infy.prime.RestWithJPA.CarrierFile,
    messageTemplate=
    '{javax.validation.constraints.Min.message}'
  }
  ConstraintViolationImpl
  {
    interpolatedMessage=
    'length must be between 1 and 20',
    propertyPath=accountID,
    rootBeanClass=class
    com.org.infy.prime.RestWithJPA.CarrierFile,
    messageTemplate=
    '{org.hibernate.validator.constraints.Length.message}'
  }
]

Request if anyone can help me on this or atleast give me an alternative to validate the request in a more efficient manner.

PS: I don't want to validate it field by field.

OneMoreError :

You can do something like this: Say this is the request class:

public class DummyRequest {

    @NotNull
    private String  code;

    @NotNull
    private String  someField;

    @NotNull
    private String  someOtherField;

    @NotNull
    private Double  length;

    @NotNull
    private Double  breadth;

    @NotNull
    private Double  height;

    // getters and setters
}

Then, you can write your own generic validate method which will give a "less verbose" constraint violation message, like this:

public static <T> List<String> validate (T input) {
    List<String> errors = new ArrayList<>();
    Set<ConstraintViolation<T>> violations = Validation.buildDefaultValidatorFactory().getValidator().validate(input);
    if (violations.size() > 0) {
        for (ConstraintViolation<T> violation : violations) {
            errors.add(violation.getPropertyPath() + " " + violation.getMessage());
        }
    }
    return errors;
}

Now, you can validate and check if your request contains any error or not. If yes, you can print it (or send back an invalid request message).

public static void main (String[] args) {
    DummyRequest request = new DummyRequest();
    request.setCode("Dummy Value");
    List<String> validateMessages = validate(request);
    if (validateMessages.size() > 0 ) {
        for (String validateMessage: validateMessages) {
            System.out.println(validateMessage);
        }
    }
}


Output:
--------
height may not be null
length may not be null
someField may not be null
someOtherField may not be null
breadth may not be null

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=103897&siteId=1