SpringbootJackson验证与Validated annotation不起作用

1sbrub3j  于 12个月前  发布在  Spring
关注(0)|答案(1)|浏览(270)

我有这个API控制器接口:

ResponseEntity<OkDTO> internal(@RequestBody @Validated MassPostDTO  dto  , HttpServletRequest req) throws Exception;

字符串
这个MassPostDTO模型:

@IMassValidator
public class MassPostDTO  implements Serializable { 
     
    private static final long serialVersionUID = 1L;
    
    @Valid
    @JsonProperty(value="idSub", required=false)
    private String idSub;
    ....


如果你看到了,我有@IMassValidator:

@Constraint(validatedBy = MassValidator.class)
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    public @interface IMassValidator {
    
        String message() default "data";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}


问题是,如果我有,在我的请求主体中,属性“idSub”声明为null,例如{“idSub”:null,“otherVars”:....... }我有一个Jackson错误Map器:

Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: null; nested exception is com.fasterxml.jackson.databind.JsonMappingException: N/A
 at [Source: (PushbackInputStream); line: 1, column: 27] (through reference chain: MassPostDTO["idSub"])]


但如果我的请求体是:{“otherVars”:....,...}代码工作
我能做些什么来解决这个问题呢?谢谢大家。

nle07wnf

nle07wnf1#

确保你已经用@Validated注解了你的控制器类或接口,用@Valid注解了你的参数,并且在你的项目中有spring-boot-starter-validation。遵循下面的代码片段,它应该可以工作。

@Validated
@RequestMapping(value = "/hello")
public interface OkDTO {

ResponseEntity<OkDTO> internal(@Valid @RequestBody MassPostDTO dto, HttpServletRequest req) throws Exception;
}

字符串

相关问题