Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly use Jackson @JSONView to exclude specific properties from default serialization?

Tags:

jackson

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?

like image 543
E-Riz Avatar asked Jul 06 '15 15:07

E-Riz


People also ask

How do I ignore unknown properties on Jackson?

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.

How do you ignore certain fields based on a serializing object to JSON?

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.

How do I ignore JSON property based on condition?

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.


1 Answers

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

like image 120
jazd Avatar answered Oct 07 '22 17:10

jazd