带有 Validated 注解的 Springboot Jackson 验证不起作用

Springboot Jackson validation with Validated annotation not work

提问人:Alex 提问时间:10/14/2023 更新时间:10/21/2023 访问量:43

问:

我有这个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”声明为空, 例如 { “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 杰克逊数据绑定

评论

0赞 Jorn 10/14/2023
听起来它在进行验证之前解析 JSON 失败。很难从部分堆栈跟踪中判断问题到底是什么,但它很可能与原始 JSON 和 DTO 本身有关。
0赞 Alex 10/15/2023
您好,@Jorn感谢您的回复。我已经暂时用 json 属性注释解决了这个问题,默认值是该字段永远不为 null。notnull 注解对我不起作用,并且还全局设置了 jackson 在反序列化时忽略 not null 字段,不起作用。

答:

0赞 Jay Yadav 10/21/2023 #1

确保已将控制器类或接口注释为 和参数,并在项目中注释了参数。 按照下面的代码片段,它应该可以工作。@Validated@Validspring-boot-starter-validation

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

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