I have a Spring Boot 2.3.2.RELEASE
WebFlux application. I have some JPA entities that are returned as part of the RESTful API responses.
The problem is that as I add methods (that exposes behavior) to these JPA entities, those return types/values are also being sent back, and I would like to avoid that.
Basically, what I'm looking for is to configure Jackson in such a way to only (de)serialize the class fields/members and anything annotated with @JsonProperty
. I can also go with the approach of ignoring everything by default, and placing @JsonProperty
on the members that I want to (de)serialize.
Note also:
Those classes have no setters, and usually there is no constructor (except for the required no-arguments one). They used a builder most of the times.
I know I can just annotate those methods with @JsonIgnore
, but there will be a lot of those, so I wonder if there is another solution that includes only the fields/members (of the classes) and anything annotated with @JsonProperty
.
The possibilities depend on the actual code you have but you could check out visibility . You could configure your ObjectMapper
like:
om.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
om.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE);
Then with class like below serialization would be done as stated in comments:
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 :)";
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.