8

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.

Jonathan
  • 1,078
  • 11
  • 9

5 Answers5

5

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.

Faron
  • 1,354
  • 10
  • 23
  • 1
    I am investigating the possibility of using a custom AnnotationIntrospector to handle this use-case. I'll add another answer if I can get it working. – Faron Mar 02 '17 at 01:03
  • @Vinit Gaikwad He couldn't because introspection occurs once per class. You won't be able to have logic determined dynamically with an AnnotationIntrospector – Dmitry Senkovich Jul 18 '17 at 22:05
  • @VinitGaikwad The project that needed this functionality was placed on hold to address a higher priority project. Once I return to this project, I'll give it another look. – Faron Jul 21 '17 at 14:41
  • @VinitGaikwad I added another answer describing how I solved this problem. I'm sorry it took so long to get back to this. – Faron Sep 04 '17 at 14:37
1

I have a need to exclude certain fields based on the caller's permissions. For example, an employee's profile may contain his taxpayer id, which is considered sensitive information and should only be serialized if the caller is a member of the Payrole department. Since I'm using Spring Security, I wish to integrate Jackson with the current security context.

public class EmployeeProfile {
    private String givenName;
    private String surname;
    private String emailAddress;

    @VisibleWhen("hasRole('PayroleSpecialist')")
    private String taxpayerId;
}

The most obvious way to do this is to Jackson's filter mechanism but it has a few limitations:

  1. Jackson does not support nested filters so adding an access filter prohibits using filters for any other purpose.
  2. One cannot add Jackson annotations to existing, third-party classes.
  3. Jackson filters are not designed to be generic. The intent is to write a custom filter for each class you wish to apply filtering. For example, I you need to filter classes A and B, then you have to write an AFilter and a BFilter.

For my use-case, the solution is to use a custom annotation introspector in conjunction with a chaining filter.

public class VisibilityAnnotationIntrospector extends JacksonAnnotationIntrospector {
    private static final long serialVersionUID = 1L;

    @Override
    public Object findFilterId(Annotated a) {
        Object result = super.findFilterId(a);
        if (null != result) return result;

        // By always returning a value, we cause Jackson to query the filter provider.
        // A more sophisticated solution will introspect the annotated class and only
        // return a value if the class contains annotated properties.
        return a instanceof AnnotatedClass ? VisibilityFilterProvider.FILTER_ID : null;
    }
}

This is basically a copy SimpleBeanProvider that replaces calls to include with calls to isVisible. I'll probably update this to use a Java 8 BiPredicate to make the solution more general but works for now. This class also takes another filter as an argument and will delegate to it the final decision on whether to serialize the field if the field is visible.

public class AuthorizationFilter extends SimpleBeanPropertyFilter {
    private final PropertyFilter antecedent;

    public AuthorizationFilter() {
        this(null);
    }

    public AuthorizationFilter(final PropertyFilter filter) {
        this.antecedent = null != filter ? filter : serializeAll();
    }

    @Deprecated
    @Override
    public void serializeAsField(Object bean, JsonGenerator jgen, SerializerProvider provider, BeanPropertyWriter writer) throws Exception {
        if (isVisible(bean, writer)) {
            this.antecedent.serializeAsField(bean, jgen, provider, writer);
        } else if (!jgen.canOmitFields()) { // since 2.3
            writer.serializeAsOmittedField(bean, jgen, provider);
        }
    }

    @Override
    public void serializeAsField(Object pojo, JsonGenerator jgen, SerializerProvider provider, PropertyWriter writer) throws Exception {
        if (isVisible(pojo, writer)) {
            this.antecedent.serializeAsField(pojo, jgen, provider, writer);
        } else if (!jgen.canOmitFields()) { // since 2.3
            writer.serializeAsOmittedField(pojo, jgen, provider);
        }
    }

    @Override
    public void serializeAsElement(Object elementValue, JsonGenerator jgen, SerializerProvider provider, PropertyWriter writer) throws Exception {
        if (isVisible(elementValue, writer)) {
            this.antecedent.serializeAsElement(elementValue, jgen, provider, writer);
        }
    }

    private static boolean isVisible(Object pojo, PropertyWriter writer) {
        // Code to determine if the field should be serialized.
    }

}

I then add a custom filter provider to each instance of ObjectMapper.

@SuppressWarnings("deprecation")
public class VisibilityFilterProvider extends SimpleFilterProvider {
    private static final long serialVersionUID = 1L;
    static final String FILTER_ID = "dummy-filter-id";

    @Override
    public BeanPropertyFilter findFilter(Object filterId) {
        return super.findFilter(filterId);
    }

    @Override
    public PropertyFilter findPropertyFilter(Object filterId, Object valueToFilter) {
        if (FILTER_ID.equals(filterId)) {
            // This implies that the class did not have an explict filter annotation.
            return new AuthorizationFilter(null);
        }

        // The class has an explicit filter annotation so delegate to it.
        final PropertyFilter antecedent = super.findPropertyFilter(filterId, valueToFilter);
        return new VisibilityPropertyFilter(antecedent);
    }
}

Finally, I have a Jackson module that automatically registers the custom annotaion introspector so I don't have to add it to each ObjectMapper instance manually.

public class FieldVisibilityModule extends SimpleModule {
    private static final long serialVersionUID = 1L;

    public FieldVisibilityModule() {
        super(PackageVersion.VERSION);
    }

    @Override
    public void setupModule(Module.SetupContext context) {
        super.setupModule(context);
        // Append after other introspectors (instead of before) since
        // explicit annotations should have precedence
        context.appendAnnotationIntrospector(new VisibilityAnnotationIntrospector());
    }
}

There are more improvements that can be made and I still have more unit tests to write (e.g., handling arrays and collections) but this is the basic strategy I used.

Faron
  • 1,354
  • 10
  • 23
0

You can try this approach for the same purpose:

@Entity
@Inheritance(
    strategy = InheritanceType.SINGLE_TABLE
)
@DiscriminatorColumn(
    discriminatorType = DiscriminatorType.STRING,
    length = 2
)
@Table(
    name = "project"
)
@JsonTypeInfo(
    use = Id.CLASS,
    include = As.PROPERTY,
    property = "@class"
)
@JsonSubTypes({
    @Type(
        value = BasicProject.class,
        name = "basicProject"
    ),
    @Type(
        value = AdvanceProject.class,
        name = "advanceProject"
    )})
public abstract class Project {
    private Long id;
    private Long version;

}

@Entity
@DiscriminatorValue("AD")
public class AdvanceProject extends Project {
    private String name;
    private String description;
}

@Entity
@DiscriminatorValue("BS")
public class BasicProject extends Project {
    private String name;
}
NNguyen
  • 216
  • 2
  • 7
0

I don't think you will make it work. I was trying and these are results of my investigation, maybe it will be helpful.

First of all, as @Faron noticed, the @JsonFilterannotation is applied for the class being annotated not a field.

Secondly, I see things this way. Let's imagine, somewhere in Jackson internals you are able to get the actual field. You can figure out if there is the annotation using Java Reflection API. You can even get the filter name. Then you get to the filter and pass the field value there. But it happens at runtime, how will you get the corresponding JsonSerializer of the field type if you decide to serialize the field? It is impossible because of type erasure.

The only alternative I see is to forget about dynamic logic. Then you can do the following things:

1) extend JacksonAnnotationIntrospector (almost the same as implement AnnotationIntrospector but no useless default code) overriding hasIgnoreMarker method. Take a look at this answer

2) criminal starts here. Kinda weird way taking into account your initial goal but still: extend BeanSerializerModifier and filter out fields there. An example can be found here. This way you can define serializer that actually doesn't serialize anything (again, I understand how strange it is but maybe one will find it helpful)

3) similar to the approach above: define useless serializer based on BeanDescription implementing ContextualSerializer's createContextual method. The example of this magic is here

Dmitry Senkovich
  • 5,521
  • 8
  • 37
  • 74
0

Thanks to this really good blog, I was able to use @JsonView to filter out specific fields from an entity bean based on some custom logic that is determined at runtime.

Since the @JsonFilter does not apply for the fields within a class, I found this to be a cleaner workaround.

Here is the sample code:

@Data
@AllArgsConstructor
public class TestEntity {
    private String a;
    @JsonView(CustomViews.SecureAccess.class)
    private Date b;
    @JsonView(CustomViews.SecureAccess.class)
    private Integer c;
    private List<String> d;
}

public class CustomViews {
    public static interface GeneralAccess {}
    public static interface SecureAccess {}

    public static class GeneralAccessClass implements GeneralAccess {}
    public static class SecureAccessClass implements SecureAccess, GeneralAccess {}

    public static Class getWriterView(final boolean hasSecureAccess) {
        return hasSecureAccess
            ? SecureAccessClass.class
            : GeneralAccessClass.class;
    }
}

@Test
public void test() throws JsonProcessingException {
        final boolean hasSecureAccess = false; // Custom logic resolved to a boolean value at runtime.
        final TestEntity testEntity = new TestEntity("1", new Date(), 2, ImmutableList.of("3", "4", "5"));
        final ObjectMapper objectMapper = new ObjectMapper().enable(MapperFeature.DEFAULT_VIEW_INCLUSION);

        final String serializedValue = objectMapper
                .writerWithView(CustomViews.getWriterView(hasSecureAccess))
                .writeValueAsString(testEntity);

        Assert.assertTrue(serializedValue.contains("a"));
        Assert.assertFalse(serializedValue.contains("b"));
        Assert.assertFalse(serializedValue.contains("c"));
        Assert.assertTrue(serializedValue.contains("d"));
}
Shankar Raju
  • 4,356
  • 6
  • 33
  • 52