16

I would like to use Jackson's Tree Model with Java 8 stream API, like so:

JsonNode jn = new ObjectMapper().readValue(src, JsonNode.class);
return jn.stream().anyMatch(myPredicate);

However, JsonNode does not seem to implement stream() and I could not find any standard helpers to do so.

JsonNode implements Iterable, so I can achieve the same results with Google Guava:

JsonNode jn = new ObjectMapper().readValue(src, JsonNode.class);
return Iterables.find(jn, myPredicate);

but what about pure Java solution?

vitaly
  • 2,755
  • 4
  • 23
  • 35
  • You can't really do a java stream on a JSON graph can you, at least if you do if would have to be limited to a sequential stream and even then I'm not sure that it makes much sense. In parallel you could have child nodes arriving before their parents, kind of strange. Perhaps you are thinking about streaming a list of top level objects converted to POJOs. That question seems to have answered here: https://stackoverflow.com/questions/32683785/create-java-8-stream-from-arraynode – K.Nicholas Feb 19 '18 at 01:53
  • Hey, @karl-nicholas. I did mean reading a sequence from a node (be it an object or array). However, the question is about Jackson Tree Model which has nothing to do with POJOs. The accepted answer is exactly what I needed. As for streaming a graph: a JSON document is a very special kind of a graph (a tree) and sure it can be traversed, e.g. breadth- or depth-first. – vitaly Feb 20 '18 at 05:14
  • Sure, a tree can be traversed but isn't streaming supposed to be the same object? If I stream a tree traversal you get different objects for each property, e.g., dates, int, floats, etc? I understand everything is a JsonNode but that is a wrapper class. If you don't care what's in the node, or are going to filter on something, yea, could be handy I suppose. Anyway, I don't know what you're trying to do, so no worries, I was just considering the question about streaming tree structures in general. Glad you got what you were looking for. – K.Nicholas Feb 20 '18 at 07:24

1 Answers1

49

JsonNode implements Iterable, so it has a spliterator(). You can use

StreamSupport.stream(jn.spliterator(), false /* or whatever */);

to get a Stream.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724