验证 Jackson 中的嵌套对象

nix*_*get 0 java validation spring json jackson

我有一个 spring 项目并使用 jackson 进行 json 序列化和反序列化。

我定义了这些 DTO,

CertManDTO,

public class CertManDTO implements Serializable {

    private static final long serialVersionUID = 1L;

    private Long id;

    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    private UUID certificateId;

    @NotNull
    private Long orgId;

    @NotNull
    private CertificateType certificateType;

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @NotNull
    private PublicCertificateDTO publicCertificate;

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private PrivateCertificateDTO privateCertificate;

    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    private ZonedDateTime expiryDate;

    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    private ZonedDateTime createdDate;

    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    private ZonedDateTime updatedDate;

    // Getters and setters
}
Run Code Online (Sandbox Code Playgroud)

PublicCertificateDTO,

public class PublicCertificateDTO implements Serializable {

    private static final long serialVersionUID = 1L;

    @JsonIgnore
    private Long id;

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @NotNull
    private String certificate;

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @NotNull
    private String dnsZone;

    // Getters and setters
}
Run Code Online (Sandbox Code Playgroud)

PrivateCertificateDTO,

public class PrivateCertificateDTO implements Serializable {

    private static final long serialVersionUID = 1L;

    @JsonIgnore
    private Long id;

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String pkcs12;

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String privateCertificatePassword;

    // Getters and setters
}
Run Code Online (Sandbox Code Playgroud)

您可以在上面看到我已经@NotNull为字段certificate&设置了注释dnzZone

但是发布这个 JSON 似乎解析成功。这只发生在嵌套对象上。

{  
   "orgId":"1001",
   "certificateType":"Single Use",
   "privateCertificate":{  
      "pkcs12":"test",
      "certificatePassword":"Test"
   },
   "publicCertificate":{  

   }
}
Run Code Online (Sandbox Code Playgroud)

如果我发布以下内容,它将无法通过@NotNull设置的验证publicCertificate

{  
   "orgId":"1001",
   "certificateType":"Single Use",
   "privateCertificate":{  
      "pkcs12":"test",
      "certificatePassword":"Test"
   }
}
Run Code Online (Sandbox Code Playgroud)

我已经@Valid设定了@RequestBodyRestController

知道是什么原因造成的吗?

Mik*_*yna 7

您似乎忘记向@Valid嵌套的 DTO添加注释。试试下面的代码:

@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@NotNull
@Valid
private PublicCertificateDTO publicCertificate;
Run Code Online (Sandbox Code Playgroud)