gpt4 book ai didi

java - 忽略单元测试的 Jackon JsonProperty 访问

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:12:09 24 4
gpt4 key购买 nike

我使用 Jackson 对我的 Spring Boot 项目进行序列化/反序列化。

我有一个具有以下结构的 DTO 对象,

public class TestDTO 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)
@Valid
@NotNull
private PublicCertificateDTO publicCertificate;

@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@Valid
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;
}

在我的单元测试中使用以下方法序列化此对象,

public static byte[] convertObjectToJsonBytes(TestDTO object)
throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

JavaTimeModule module = new JavaTimeModule();
mapper.registerModule(module);

return mapper.writeValueAsBytes(object);
}

导致具有WRITE_ONLY 访问权限的字段被忽略(原因很明显)。所以在序列化对象中,我看到了 publicCertificateprivateCertificate 的空值。

我确实尝试设置 mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)

有没有其他方法可以忽略单元测试的这些属性?

最佳答案

虽然指定的解决方案有效,但对于要求而言,它有点矫枉过正。如果您只想覆盖注释,则不需要自定义序列化程序。 jackson 有一个 mixin feature对于这些琐碎的要求

考虑以下简化的 POJO:

public class TestDTO
{
public String regularAccessProperty;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
public String writeAccessProperty;
}

如果您想覆盖 @JsonProperty 注释,您可以创建另一个 POJO,它有一个具有完全相同名称(或相同的 getter/setter 名称)的变量:

// mixin class that overrides json access annotation
public class UnitTestDTO
{
@JsonProperty(access = JsonProperty.Access.READ_WRITE)
public String writeAccessProperty;
}

您通过一个简单模块将原始 POJO 和混入相关联:

simpleModule.setMixInAnnotation(TestDTO.class, UnitTestDTO.class);

关于java - 忽略单元测试的 Jackon JsonProperty 访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42775127/

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