Configuring Jackson to use only field annotations
Once the annotations are placed on the fields, you can configure ObjectMapper
to use only the fields annotations, ignoring the annotations of getters and setters methods:
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
Jackson mix-in annotations
It's a great alternative when modifying your POJOs is not an option. You can think of it as a kind of aspect-oriented way of adding more annotations during runtime, to augment statically defined ones.
Define a mix-in annotation interface (class would do as well):
public interface FooMixIn {
@JsonIgnore
String getBar();
}
Then configure ObjectMapper
to use the defined interface (or class) as a mix-in for your POJO:
ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT)
.addMixIn(Foo.class, FooMixIn.class);
Here are some usage considerations:
- All annotation sets that Jackson recognizes can be mixed in.
- All kinds of annotations (member method, static method, field, constructor annotations) can be mixed in.
- Only method (and field) name and signature are used for matching annotations: access definitions (
private
, protected
, ...) and method implementations are ignored.
For more details, check this page.