I am trying to iterate through JsonNode tree, and I have written a following snippet that iterate over children nodes of root node and gets the text out of it, which I assume will be a field name.
JsonNode rootNode = new ObjectMapper().readTree(jsonParser);
for (JsonNode node : rootNode){
String fieldName = node.asText(); // <- is it safe to assume this?
JsonNode value = node.get(fieldName);
}
I have read this similar post, but the accepted answer simply doesn't work because both fields
and fieldNames
return iterator
, which cannot be iterated through a foreach
loop just by itself as far as I know.
The other most upvoted answer works, but I was wondering if the above snippet's assumption is still valid.
No.
The javadoc of JsonNode#iterator()
states
Same as calling
elements();
implemented so that convenience "for-each" loop can be used for looping over elements of JSON Array constructs.
And the javadoc of JsonNode#elements()
states
Method for accessing all value nodes of this Node, iff this node is a JSON Array or Object node. In case of Object node, field names (keys) are not included, only values. For other types of nodes, returns empty iterator.
So the elements returned are the values of each key-value pair of an object node. For array nodes, it's the array elements.