jackson 忽略单元测试的Jackon JsonProperty访问

x4shl7ld  于 2022-11-08  发布在  其他
关注(0)|答案(5)|浏览(147)

我使用Jackson对我的Sping 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)
是否有其他方法可以忽略单元测试的这些属性?

iaqfqrcu

iaqfqrcu1#

虽然指定的解决方案可以工作,但它对于需求来说是一个大材小用。如果您想要的只是覆盖注解,则不需要自定义序列化程序。Jackson有一个mixin feature来满足这种琐碎的需求
请考虑以下简化的POJO:

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

如果要覆盖@JsonProperty注解,请创建另一个POJO,该POJO具有完全相同的名称(或相同的getter/setter名称)的变量:

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

通过一个时间表模块将原始POJO和mixin关联起来:

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

aor9mmx12#

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

**解决方案:**在convertObjectToJsonBytes方法中,可以用途:

mapper.disable(MapperFeature.USE_ANNOTATIONS);

**参考:**Map器功能.USE_ANNOTATIONS

/**
 * Feature that determines whether annotation introspection
 * is used for configuration; if enabled, configured
 * {@link AnnotationIntrospector} will be used: if disabled,
 * no annotations are considered.
 *<p>
 * Feature is enabled by default.
 */
USE_ANNOTATIONS(true),

**注意:**这将禁用给定ObjectMapper的所有注解。

iyzzxitl

iyzzxitl3#

通过为JUnit测试添加一个自定义序列化程序解决了这个问题。
因此,对于TestDTO,我添加了如下所示的串行化程序。

private class TestJsonSerializer extends StdSerializer<TestDTO> {
    public TestJsonSerializer() {
        this(null);
    }

    public TestJsonSerializer(Class<TestDTO> t) {
        super(t);
    }

    @Override
    public void serialize(TestDTO value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeStartObject();
        gen.writeNumberField("orgId", value.getOrgId());
        gen.writeStringField("certificateType", value.getCertificateType().getType());
        if (value.getPublicCertificate() != null) {
            gen.writeObjectField("publicCertificate", value.getPublicCertificate());
        }
        if (value.getPrivateCertificate() != null) {
            gen.writeObjectField("privateCertificate", value.getPrivateCertificate());
        }
        gen.writeObjectField("expiryDate", value.getExpiryDate());
        gen.writeObjectField("createdDate", value.getCreatedDate());
        gen.writeObjectField("updatedDate", value.getUpdatedDate());
        gen.writeEndObject();
    }
}

我接着补充道:

ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(TestDTO.class, new TestJsonSerializer());
mapper.registerModule(simpleModule);

以类似方式为嵌套对象publicCertificateprivateCertificate添加和注册自定义序列化程序。

jdzmm42g

jdzmm42g4#

另一个解决方案是用一个简单的自定义类覆盖注解检查器。这是最简单的示例

ObjectMapper mapper = new ObjectMapper().setAnnotationIntrospector(new JacksonAnnotationIntrospector() {
     @Override
     public JsonProperty.Access findPropertyAccess(Annotated m) {
           return null;
     }
});

其他Sping Boot**@自动连线对象Map器**的解决方案:

1.使用专用类,以便它可重用且可读性更强:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.introspect.Annotated;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;

public class IgnoreReadOnlyFieldsAnnotationInspector extends JacksonAnnotationIntrospector {
    @Override
    public JsonProperty.Access findPropertyAccess(Annotated m) {
        return null;
    }
}

1.在测试中使用@BeforeEach(或她的老朋友)

public class AmazingTest {
  @Autowired
  ObjectMapper mapper;

 @BeforeEach
    void beforeAll(){
        // need to copy because the autowired mapper in test and the object mapper in code under test are the same instance
        mapper = objectMapper.copy();
        mapper.setAnnotationIntrospector(new IgnoreReadOnlyFieldsAnnotationInspector());
    }
}
fcy6dtqo

fcy6dtqo5#

这里举一个简单的例子

@ToString
@Getter
@Setter
public class Account implements Cloneable {

    @JsonProperty(access = Access.WRITE_ONLY)
    private Integer accountId;
    private String accountType;
    private Long balance;

public AccountTest clone() {
    AccountTest test = new AccountTest();
    test.setAccountId(this.accountId);
    test.setAccountType(this.accountType);
    test.setBalance(this.balance);
    return test;
}

}

@ToString
@Getter
@Setter
public class AccountTest {

    private Integer accountId;
    private String accountType;
    private Long balance;
}

    public static void main(String[] args) {
              ObjectMapper mapper = new ObjectMapper();
    try {
        Account account = new Account();
        account.setAccountId(1999900);
        account.setAccountType("Saving");
        account.setBalance(2433l);
        AccountTest accountTest = account.clone();
        System.out.println(account);

        byte[] accountBytes = mapper.writeValueAsBytes(account);
        System.out.println(new String(accountBytes));

        byte[] accountTestBytes = mapper.writeValueAsBytes(accountTest);
        System.out.println(new String(accountTestBytes));
    } catch (IOException e) { }

    }

}

相关问题