Given a JSON-mapped class like this:
public class Person {
@JsonProperty
String getName() { ... }
@JsonProperty @JsonView(SpecialView.class)
String getId() { ... }
}
I need to include only the name
property when when using "normal" serialization (ie, no view specified), and include both properties when serializing using SpecialView
. But when I do
objectMapper.writeValueAsString(object)
(ie, not specifying any view), the id
property is included.
If I do
objectMapper..writerWithView(Object.class).writeValueAsString(object)
then it behaves as expected. Problem is, I don't control all the code that's doing serialization so I can't force it all to specify a view.
When I stepped through the Jackson source code (v 2.5.4), I see that com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields()
does not use the _filteredProps
if there is no "active view":
if (_filteredProps != null && provider.getActiveView() != null) {
props = _filteredProps;
} else {
props = _props;
}
It seems strange that serialization would not respect @JsonView
when no view is specified. Am I missing something?
Is there a way to achieve what I want?
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.
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.
I ran across the same problem. It seems like Jackson totally ignores @JsonView annotations unless a view is specified. To get the behaviour you are after give your mapper a default view of Object.class.
mapper.setConfig(mapper.getSerializationConfig().withView(Object.class));
Note that you can also exclude fields without @JsonView annotation's using
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
This is with Jackson 2.6.3
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