Hi,
I have a container-like record which contains a list of item records which I want to filter, the problem is that the content filter class is not being instantiated at all.
That is, I have this:
record Item(long key, String value) {};
record Container(@JsonInclude(value = Include.NON_NULL, content = Include.CUSTOM, contentFilter = EmptyValueFilter.class) List<Item> fields) {};
class EmptyValueFilter {
@Override
public boolean equals(Object obj) {
try {
Method method = obj.getClass().getMethod("value");
return method.invoke(obj) == null;
} catch (Exception e) {
return false;
}
}
}
@Test
public void test() throws IOException {
Container input = new Container(List.of(
new Item(123L, "avalue"),
new Item(456L, null)
));
new ObjectMapper().writerWithDefaultPrettyPrinter().writeValue(System.out, input);
}
Based on this I was expecting:
{
"fields" : [ {
"key" : 123,
"value" : "avalue"
}
}
but I am getting this:
{
"fields" : [ {
"key" : 123,
"value" : "avalue"
}, {
"key" : 456,
"value" : null
} ]
}
Things I 've tried:
- Jackson 2.19.1 and 2.19.0 (no change)
- Convert the records to Java classes instead (no change)
If I switch the contentFilter
to a valueFilter
it is properly invoked (but obviously doesn't do what I want).
I know that I can implement a custom Jackson serializer for the whole list, but this contentFilter
seems more elegant :)
Comment From: pjfanning
You could be waiting months for 2.20.0 to come out. So elegance may be expensive. The Jackson team may end up agreeing with your assessment but don't expect an expedited release.
Comment From: dmandalidis
@pjfanning I won't be literally waiting for a release since there's a valid workaround for this. I only wanted to clarify whether this is a valid bug or not. Thanks
Comment From: cowtowncoder
It seems like it should work. Could you try equivalent POJO case to see if that works?
Comment From: cowtowncoder
Also: wrong repo, will transfer to correct one.
Comment From: dmandalidis
It seems like it should work. Could you try equivalent POJO case to see if that works?
I did. Same behavior :/
Comment From: JooHyukKim
As per document from 2.19, It seems ...
- Map
type is supported.
- List
is be supported yet
Comment From: cowtowncoder
Ahh. I should have read this with thought: @JooHyukKim is right, content filtering only applies to POJOs and Map
s -- basically name-indexed types.
I suspect there might be another issue for extending support to Containers (arrays, Collection
s), but nothing actively being developed as far as I know.
Comment From: JooHyukKim
@cowtowncoder Could be a 3.x feature idea? Maybe backport ias needed