If an Iterator is more useful...
...you can also use the elements()
method of ArrayNode
. Example see below.
sample.json
{
"first": [
"Some string ...",
"Some string ..."
],
"second": [
"Some string ..."
]
}
So, the List<String>
is inside one of the JsonNode
s.
Java
When you convert that inner node to an ArrayNode
you can use the elements()
method, which returns an Iterator of JsonNodes.
File file = new File("src/test/resources/sample.json");
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(file);
ArrayNode arrayNode = (ArrayNode) jsonNode.get("first");
Iterator<JsonNode> itr = arrayNode.elements();
// and to get the string from one of the elements, use for example...
itr.next().asText();
New to Jackson Object Mapper?
I like this tutorial:
https://www.baeldung.com/jackson-object-mapper-tutorial
Update:
You can also use .iterator()
method of ArrayNode
. It is the same:
Same as calling
.elements()
; implemented so that convenience "for-each" loop can be
used for looping over elements of JSON Array constructs.
from the javadocs of com.fasterxml.jackson.core:jackson-databind:2.11.0