问题描述
我有一个Spring Boot 2.3.2.RELEASE
WebFlux应用程序。我有一些JPA实体是作为RESTful API响应的一部分返回的。
问题在于,当我向这些JPA实体添加方法(公开行为)时,这些返回类型/值也被发送回,我想避免这种情况。
基本上,我要寻找的是配置Jackson的方式,以便仅(反)序列化类字段/成员以及所有带有@JsonProperty
注释的内容。我还可以采用以下方法:默认情况下忽略所有内容,并将@JsonProperty
放在我要反序列化的成员上。
另请注意:
解决方法
是否可用取决于您的实际代码,但是您可以查看可见性。您可以像这样配置ObjectMapper
:
om.setVisibility(PropertyAccessor.FIELD,JsonAutoDetect.Visibility.ANY);
om.setVisibility(PropertyAccessor.GETTER,JsonAutoDetect.Visibility.NONE);
然后按照注释中的说明完成类似以下序列化的类:
public static class TestClass {
@Getter // getter is generated but ignored
// because visibility for GETTER is NONE
// still serialized because visibility for FIELD is ANY
private String fieldThatShouldBeSerialized = "It is OK to serialize me :)";
// not serialized because visibility for GETTER is NONE
public String getMethodThatShouldNotBeSerialized() {
return "It is NOT OK to serialize me :(";
}
@JsonProperty // serialized because explicitly asked (not auto)
public String methodThatShouldBeSerialized() {
return "It is OK to serialize me also :)";
}
@JsonProperty // serialized because explicitly asked (not auto)
// even it is a "getter"
public String getAnotherMethodThatShouldBeSerialized() {
return "It is OK to serialize me also :)";
}
}