Springboot Jackson 验证与 Validated 注释不起作用

问题描述 投票:0回答:1

我有这个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":....... } 我有一个杰克逊错误映射器:

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": ....,... } 代码可以正常工作

我可以做什么来解决? 感谢大家

java spring-boot jackson spring-data jackson-databind
1个回答
0
投票

确保您已使用

@Validated
注释了您的控制器类或接口,并且您的项目中有
spring-boot-starter-validation
。 按照下面的代码片段应该可以工作。

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

ResponseEntity<OkDTO> internal(@Valid @RequestBody MassPostDTO dto, HttpServletRequest req) throws Exception;
}
© www.soinside.com 2019 - 2024. All rights reserved.