Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson @JsonFilter is not getting applied when used at field or method level

Tags:

spring

jackson

I am using Spring version 4.3.3 and Jackson version 2.8.3. I am trying to filter out specific fields from an entity bean based on some custom logic that is determined at runtime. The @JsonFilter seems ideal for this type of functionality. The problem is that when I put it at the field or method level, my custom filter never gets invoked. If I put it at the class level, it gets invoked just fine. I don't want to use it at the class level though since then I would need to separately maintain the list of hardcoded field names that I want to apply the logic to. As of Jackson 2.3, the ability to put this annotation at the field level is supposed to exist.

Here is the most basic custom filter without any custom logic yet:

public class MyFilter extends SimpleBeanPropertyFilter {

@Override
protected boolean include(BeanPropertyWriter beanPropertyWriter) {
    return true;
}

@Override
protected boolean include(PropertyWriter propertyWriter) {
    return true;
}

}

Then I have the Jackson ObjectMapper configuration:

public class MyObjectMapper extends ObjectMapper {

    public MyObjectMapper () {
        SimpleFilterProvider filterProvider = new SimpleFilterProvider();
        filterProvider.addFilter("myFilter", new MyFilter());
        setFilterProvider(filterProvider);
    }
}

Then finally I have my entity bean:

@Entity
public class Project implements Serializable {

    private Long id;
    private Long version;
    @JsonFilter("myFilter") private String name;
    @JsonFilter("myFilter") private String description;

    // getters and setters

}

If I move the @JsonFilter annotation to the class level where @Entity is, the filter at least gets invoked, but when it is at the field level like in the example here, it never gets invoked.

like image 696
Jonathan Avatar asked Sep 29 '16 15:09

Jonathan


Video Answer


1 Answers

I have the same need but after examining the unit tests I discovered that this is not the use-case covered by annotating a field.

Annotating a field invokes a filter on the value of the field not the instance containing the field. For example, imagine you have to classes, A and B, where A contains a field of type B.

class A {
    @JsonFilter("myFilter") B foo;
}

Jackson applies "myFilter" to the fields in B not in A. Since your example contains fields of type String, which has no fields, Jackson never invokes your filter.

like image 158
Faron Avatar answered Oct 11 '22 13:10

Faron