Teodor Dimitrov Teodor Dimitrov - 1 year ago 156
JSON Question

Spring Boot Hibernate Constraint Validator

I would like to make a field validation without persisting data by using Spring Boot and Hibernate Validator.

public class RoomDto {

private long id;

private int beds;

private double size;

private String flatBasicStringDto;

I am parsing a DTO from JSON by using GSON:

RoomDto guestRoom = this.jsonParser.read(RoomDto.class, "/files/input/room.json");

I would like to get an error when flatBasicStringDto is missing in the JSON file.

I have tried many configurations but nothing works so far.


Any ideas how to deal with this issue?

Answer Source

You can use method level validation using @valid annotation. However, you need your DI container to hook in with the validation framework. A comprehensive example using spring is at http://www.mkyong.com/spring-mvc/spring-3-mvc-and-jsr303-valid-example/.

If you dont want to use a DI containter, you can use something like this to get the validation errors:

 ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
 Validator validator = factory.getValidator();
 Set<ConstraintViolation<RoomDto>> errors = validator.validate(guestRoom);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download