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?
Jackson API provides two ways to ignore unknown fields, first at the class level using @JsonIgnoreProperties annotation and second at the ObjectMapper level using configure() method.
If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.
The Jackson @JsonIgnore annotation can be used to ignore a certain property or field of a Java object. The property can be ignored both when reading JSON into Java objects and when writing Java objects into JSON.
To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.
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"}
By changing visibility settings. This question:
how to specify jackson to only use fields - preferably globally
seems to have settings you can use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With