Is it possible to use @Valid (javax.validation.Valid)
in below scenario?
import com.fasterxml.jackson.databind.ObjectMapper; import javax.validation.Valid; import com.incident.tool.model.IncidentModel; @Service public class JsonStringToObjectConverter { public IncidentModel convertToObject(String json) throws JsonMappingException, JsonProcessingException { @Valid IncidentModel incidentModel = new ObjectMapper().readValue(json, IncidentModel.class); return incidentModel ; } }
Here JsonStringToObjectConvertor
is taking in JSON in form of String and mapping it to IncidentModel
class. I have defined few validations in IncidentModel
in below manner and I want to validate the fields mapped by ObjectMapper
in IncidentModel
before proceeding further:
@Component @Getter @Setter @ToString @NoArgsConstructor @AllArgsConstructor public class IncidentModel extends IncidentInfo { @NotEmpty private String empId; @NotEmpty @Size(min = 2, max = 30) private String empName; @NotEmpty private String title; private String description; private String assignedTo; private String severity; private String incidentNumber; private String dateCreated; private String dateClosed; private String closingNotes; }
It does not seem to work in the above format, is there any alternative to use the @Valid
in the convertToObject
method?
Thanks for your help.
Advertisement
Answer
You can do something as follows:
@Service public class JsonStringToObjectConverter { public IncidentModel convertToObject(String json) throws JsonMappingException, JsonProcessingException { IncidentModel incidentModel = new ObjectMapper().readValue(json, IncidentModel.class); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<IncidentModel>> errors = validator.validate(incidentModel); return incidentModel; } }
You could then optimize this and make ValidatorFactory factory
and Validator validator
instance variables of JsonStringToObjectConverter
so that you don’t recreate them every time you call convertToObject
method.