Nathaniel Ford Nathaniel Ford -4 years ago 157
Java Question

Filter out fields from a JsonNode

I have a Jackson

JsonNode
of sub-type
ObjectNode
:

ObjectNode node = parent.path('somepath');


node
has a number of sub-fields, such as you'd see in this json object:

{
"somepath": {
"a": 1,
"b": 2,
"c": 3,
"d": 4
}
}


So the above object
node
will have four sub-objects (all
JsonNode
/
ObjectNode
s in their own right):
a
,
b
,
c
and
d
.

Given object
node
, I'd like to filter out some of the subfields. For instance, let's say I'd like to filter out everything but some list of field names, say
["b", "c"]
. When I re-serialize the
node
object it would look like this:

{
"somepath": {
"b": 2,
"c": 3
}
}


I can think of a lot of ways where I can loop through both the field name list and the keep list, and rebuild the object, but that all seems like a lot of work and very unclear. What I'd love to use is a
Stream.filter()
type of function:

List<String> keepList = Lists.newArrayList("b", "c");
node.stream().filter( field -> keepList.contains(field.name()));


Obviously the above code doesn't work because I can't 'stream' an
ObjectNode
. Is there a way I can get this to work in a similar fashion, or am I stuck going the long way around?

Answer Source

There is a method in ObjectNode that does exactly what you want: retain. You might use it this way:

ObjectNode node = parent.path('somepath');

node = node.retain(keepList);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download