Reputation: 1745
I need the opposite of @JsonIgnore
, I need to tell Jackson to ignore all properties on an object except the the ones I annotate. I don't accidentally want someone adding a property and forget adding a @JsonIgnore
and then I expose it where I don't want to.
Anyone know how to achieve this?
Upvotes: 8
Views: 5326
Reputation: 116610
By changing visibility settings. This question:
how to specify jackson to only use fields - preferably globally
seems to have settings you can use.
Upvotes: 1
Reputation: 19231
One way of achieving something similar is to use a SimpleBeanPropertyFilter
. Filters does not solve the problem by using on the fields you wish to include but it solves the problem with simply defining which fields to be serialized.
If you assume the following POJO:
@JsonFilter("personFilter")
public class Person {
private final String firstName;
private final String lastName;
public Person(final String firstName, final String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getFullName() {
return getFirstName() + " " + getLastName();
}
public String getLastName() {
return lastName;
}
}
The POJO has two properties (firstName
and lastName
) that we DO NOT want to serialize. We only want to serialize fullName
).
As you may have noticed, the @JsonFilter
annotation at the top of the class points to a named filter that can be created like this:
// A filter that filter out all except for fullName
FilterProvider filters =
new SimpleFilterProvider().addFilter(
"personFilter",
SimpleBeanPropertyFilter.filterOutAllExcept("fullName"));
In the end, the only thing you need to do is to create your ObjectMapper
by using the following:
final ObjectMapper mapper = new ObjectMapper();
String json = mapper.writer(filters).writeValueAsString(new Person("Johnny", "Puma"));
And the string will contain:
{"fullName":"Johnny Puma"}
Upvotes: 2