jackson-databind
jackson-databind copied to clipboard
New feautre: @JsonIgnoreIf on base 2.14
Hello everyone,
We discussed this new feature already in a closed PR. It was on the wrong branch. Therefore here on branch 2.14:
In several projects (especially REST APIs) in which I used Jackson I needed the feature to ignore an Jackson property dynamically (e.g. based on authorization). I always used some kind of workaround.
So I decided to build the @JsonIgnoreIf annotation. You can specify a class extending the abstract class JsonIgnoreValidator. The usage is basically very easy.
public static class JsonIgnoreForGuests extends JsonIgnoreValidator {
@Override
public boolean ignore() {
// Example with Spring: Ignoring if there is no Authentication
return !SecurityContextHolder.getContext().getAuthentication().isAuthenticated();
}
}
Defining properties that should be checked before transfering into JSON works by:
@JsonIgnoreIf(JsonIgnoreForGuests.class)
public String sensibleData = "Lorem Ipsum";
Best regards from Germany Sebastian
Ok, I think that if this was to be merged, I'd like to make this bit more contextual, partly to allow HandlerInstantiator to be used, and partly to allow JsonIgnoreValidator to not have to rely on ThreadLocal or similar work-arounds (like static contexts). I might do some refactoring for
But what I am also thinking is this: I am not 100% sure this makes sense as an out-of-the-box feature, because you can actually implement this by custom AnnotationIntrospector already. You can either sub-class JacksonAnnotationIntrospector, or just AnnotationIntrospector and add insert/append it.
So at this point I am still evaluating whether this should be included, and if so in what form.
But I will keep thinking about it: I think the idea is good, I am just not sure how it should be supported.