gpt4 book ai didi

java - 验证 Jackson 中的嵌套对象

转载 作者:行者123 更新时间:2023-12-01 20:53:47 24 4
gpt4 key购买 nike

我有一个 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
}

公共(public)证书DTO,

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
}

私有(private)证书DTO,

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
}

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

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

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

}
}

如果我发布以下内容,验证将失败,因为 publicCertificate 设置了 @NotNull

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

我确实在 RestController 中为 @RequestBody 设置了 @Valid

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

最佳答案

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

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

关于java - 验证 Jackson 中的嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42709209/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com