Jackson how to transform JsonNode to ArrayNode without casting? Jackson how to transform JsonNode to ArrayNode without casting? arrays arrays

Jackson how to transform JsonNode to ArrayNode without casting?


Yes, the Jackson manual parser design is quite different from other libraries. In particular, you will notice that JsonNode has most of the functions that you would typically associate with array nodes from other API's. As such, you do not need to cast to an ArrayNode to use. Here's an example:

JSON:

{    "objects" : ["One", "Two", "Three"]}

Code:

final String json = "{\"objects\" : [\"One\", \"Two\", \"Three\"]}";final JsonNode arrNode = new ObjectMapper().readTree(json).get("objects");if (arrNode.isArray()) {    for (final JsonNode objNode : arrNode) {        System.out.println(objNode);    }}

Output:

"One"
"Two"
"Three"

Note the use of isArray to verify that the node is actually an array before iterating. The check is not necessary if you are absolutely confident in your datas structure, but its available should you need it (and this is no different from most other JSON libraries).


In Java 8 you can do it like this:

import java.util.*;import java.util.stream.*;List<JsonNode> datasets = StreamSupport    .stream(obj.get("datasets").spliterator(), false)    .collect(Collectors.toList())


I would assume at the end of the day you want to consume the data in the ArrayNode by iterating it. For that:

Iterator<JsonNode> iterator = datasets.withArray("datasets").elements();while (iterator.hasNext())         System.out.print(iterator.next().toString() + " "); 

or if you're into streams and lambda functions:

import com.google.common.collect.Streams;Streams.stream(datasets.withArray("datasets").elements())    .forEach( item -> System.out.print(item.toString()) )