0

在我的 Spring Rest Endpoint 中,我接收 JSON 作为包装在请求参数中的字符串。我可以使用 JSON 类的 ObjectMapper 将 JSON 字符串反序列化为对象。但是,我想验证对象的属性,即名字、姓氏是否为空或 null 以及电话号码是否为 10 位数字以及其他验证等等

我的问题是如何在 Spring Boot Rest 中实现对象的验证,而无需在 Controller 方法中使用 @Valid 注释

@PostMapping(value = "/saveEmployee")
    public ResponseEntity<?> saveEmployeeDetails(
            @Valid @RequestPart(value = "empData", required = true) String emplRegJSONString,
            @RequestParam("file") MultipartFile uploadFile, BindingResult result) {

        Status status = new Status();
        try {
            LOGGER.info("Request Body is " + emplRegJSONString);
            Long savedEmployeeRegisId = null;
            if (StringUtils.isNotBlank(emplRegJSONString)) {
                EmployeeRegistrationTbl employeeRegistrationTbl = new ObjectMapper().readValue(emplRegJSONString,
                        EmployeeRegistrationTbl.class);

               // VALIDATION SHOULD GO AHEAD HERE ON EmployeeRegistrationTbl object

            }
}
4

1 回答 1

0

您可以在 github 上使用 json-schema-validator 项目进行 spring boot。 让我们用一个例子来解释。我们尝试到达 json 对象中的一个节点,如果我们没有得到这个节点,我们的模式验证将失败并以异常捕获它。

public void validate(final ProcessingReport report,
    final  MessageBundle bundle, final FullData data)
    throws ProcessingException
{
    final String value = data.getInstance().getNode().textValue();
    try {
        UUID.fromString(value);
    } catch (IllegalArgumentException ignored) {
        report.error(newMsg(data, bundle, "invalidUUID")
            .put("input", value));
    }
}

您还可以使用正则表达式获得您想要的结果。也有例子。您可以在 github 上查看json-schema-validator 示例的示例

于 2019-03-31T11:54:46.230 回答