This will work for you :
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(json);
Map<String, String> map = new HashMap<>();
addKeys("", root, map, new ArrayList<>());
map.entrySet()
.forEach(System.out::println);
private void addKeys(String currentPath, JsonNode jsonNode, Map<String, String> map, List<Integer> suffix) {
if (jsonNode.isObject()) {
ObjectNode objectNode = (ObjectNode) jsonNode;
Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
String pathPrefix = currentPath.isEmpty() ? "" : currentPath + "-";
while (iter.hasNext()) {
Map.Entry<String, JsonNode> entry = iter.next();
addKeys(pathPrefix + entry.getKey(), entry.getValue(), map, suffix);
}
} else if (jsonNode.isArray()) {
ArrayNode arrayNode = (ArrayNode) jsonNode;
for (int i = 0; i < arrayNode.size(); i++) {
suffix.add(i + 1);
addKeys(currentPath, arrayNode.get(i), map, suffix);
if (i + 1 <arrayNode.size()){
suffix.remove(arrayNode.size() - 1);
}
}
} else if (jsonNode.isValueNode()) {
if (currentPath.contains("-")) {
for (int i = 0; i < suffix.size(); i++) {
currentPath += "-" + suffix.get(i);
}
suffix = new ArrayList<>();
}
ValueNode valueNode = (ValueNode) jsonNode;
map.put(currentPath, valueNode.asText());
}
}
For the json you gave the output will be :
name-items-name-1-2=2nditem
name-items-name-1-1=firstitem
name-items-stock-1-1=12
name-first-1=John
name-items-stock-1-2=23
company=John Company
name-last-1=Doe
Answer from Daniel Taub on Stack Overflow Top answer 1 of 4
30
This will work for you :
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(json);
Map<String, String> map = new HashMap<>();
addKeys("", root, map, new ArrayList<>());
map.entrySet()
.forEach(System.out::println);
private void addKeys(String currentPath, JsonNode jsonNode, Map<String, String> map, List<Integer> suffix) {
if (jsonNode.isObject()) {
ObjectNode objectNode = (ObjectNode) jsonNode;
Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
String pathPrefix = currentPath.isEmpty() ? "" : currentPath + "-";
while (iter.hasNext()) {
Map.Entry<String, JsonNode> entry = iter.next();
addKeys(pathPrefix + entry.getKey(), entry.getValue(), map, suffix);
}
} else if (jsonNode.isArray()) {
ArrayNode arrayNode = (ArrayNode) jsonNode;
for (int i = 0; i < arrayNode.size(); i++) {
suffix.add(i + 1);
addKeys(currentPath, arrayNode.get(i), map, suffix);
if (i + 1 <arrayNode.size()){
suffix.remove(arrayNode.size() - 1);
}
}
} else if (jsonNode.isValueNode()) {
if (currentPath.contains("-")) {
for (int i = 0; i < suffix.size(); i++) {
currentPath += "-" + suffix.get(i);
}
suffix = new ArrayList<>();
}
ValueNode valueNode = (ValueNode) jsonNode;
map.put(currentPath, valueNode.asText());
}
}
For the json you gave the output will be :
name-items-name-1-2=2nditem
name-items-name-1-1=firstitem
name-items-stock-1-1=12
name-first-1=John
name-items-stock-1-2=23
company=John Company
name-last-1=Doe
2 of 4
24
elements() gives you an iterator for subnodes and fields() gives you the properties.
With that, you can code a recursive function that walks through all nodes.
Readthedocs
jse.readthedocs.io › en › latest › utils › jackson › jacksonJsonNodeForEach.html
Jackson JsonNode.forEach() with Java 8 Consumer — Java Repositories 1.0 documentation
Jackson has provided JsonNode.forEach() method which will accept Java 8 consumer definition to iterate each node. The consumer accepts only super classes of JsonNode.
Apps Developer Blog
appsdeveloperblog.com › home › java › java json › iterate over jsonnode in java
Iterate over JsonNode in Java - Apps Developer Blog
August 12, 2022 - Here is an example program that iterates through the fields of a JsonNode and prints the field names and values: import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Iterator; import java.util.Map; class User { private String name; private String city; private String state; // constructors, getters, setters and toString() method } class Test { public static void main(String[] args) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); String json = "{\"key1\":\"value1\",\"user\":{\"name\":\"Steve\",\"city\":\"Paris\
Coderanch
coderanch.com › t › 736190 › languages › Loop-JsonNode-fields-Kotlin
Loop through a JsonNode and its fields [Kotlin] (Kotlin forum at Coderanch)
November 2, 2020 - programming forums Java Mobile ... is to be able to loop through the following JsonNode and its elements: Each iteration should present a JsonNode with its elements until no JsonNode object is found....
JanBask Training
janbasktraining.com › community › java › how-can-i-iterate-json-objects-in-java-programming-language
How can I iterate JSON objects in Java programming language? | JanBask Training Community
January 24, 2024 - ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(jsonString); Iterator fieldNames = jsonNode.fieldNames(); While (fieldNames.hasNext()) { String fieldName = fieldNames.next(); JsonNode value = jsonNode.get(fieldName); // Your logic here, for example: System.out.println(“Field: “ + fieldName + “, Value: “ + value); } } catch (Exception e) { e.printStackTrace(); } } } This above coding would use the Jackson library for parsing JSON string and then after it would help in iterating through the fields of the JSON object. You can also customize the logic within the loop to suit your particular needs and requirements like as extraction of the values and performing certain actions based on the conditions.
Java Code Geeks
javacodegeeks.com › home › enterprise java
Simplified Json Array Operations with JsonNode in Jackson
May 6, 2024 - When working with JSON arrays ([]), the ArrayNode class in Jackson is especially useful for handling Simplified Array Operations on JsonNode in Jackson, enabling efficient manipulation and traversal of JSON arrays within Java applications.
Baeldung
baeldung.com › home › json › jackson › get all the keys in a json string using jsonnode
Get all the Keys in a JSON String Using JsonNode | Baeldung
May 11, 2024 - Dapr Workflows solves this via Durable Execution which includes automatic state persistence, replaying workflows after failures and built-in resilience through retries, timeouts and error handling. In this tutorial, we'll see how to orchestrate a multi-step flow for a ride-hailing application by integrating Dapr Workflows and Spring Boot: ... In this tutorial, we’ll explore different ways to extract all the nested keys from a JSON using JsonNode.
ConcretePage
concretepage.com › jackson-api › jackson-jsonnode-foreach-with-java-8-consumer
Jackson JsonNode.forEach() with Java 8 Consumer
March 2, 2015 - package com.concretepage; import java.io.File; import java.io.IOException; import java.util.function.Consumer; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.map.ObjectMapper; public class IterateJSONwithConsumer { public static void main(String[] args) throws JsonParseException, IOException { JsonFactory jsonFactory = new JsonFactory(); JsonParser jp = jsonFactory.createJsonParser(new File("D:/cp/info.json")); jp.setCodec(new ObjectMapper()); JsonNode jsonNode = jp.readValueAsTree(); Consumer<JsonNode> data = (JsonNode node) -> System.out.println(node.asText()); jsonNode.forEach(data); } } Find the output.
Tabnine
tabnine.com › home page › code › java › com.fasterxml.jackson.databind.jsonnode
com.fasterxml.jackson.databind.JsonNode.iterator java code examples | Tabnine
" \"result\": \"test.ru\"}\n" + "}"; Iterator<JsonNode> paramsIterator = mapper.readTree(requestGood).at("/params").iterator(); List<JsonNode> paramsNodes = new ArrayList<>(); while (paramsIterator.hasNext()) {
GitHub
gist.github.com › 38f207816554b8bbffef58aa7cfebcf1
How to iterate over a Jackon JsonNode / Java Map Entry iterator in Scala · GitHub
How to iterate over a Jackon JsonNode / Java Map Entry iterator in Scala - gist:38f207816554b8bbffef58aa7cfebcf1
GitHub
github.com › FasterXML › jackson-databind › issues › 3809
Add Stream-friendly alternative to `JsoneNode.fields()`: `Set<Map.Entry<String, JsonNode>> properties()` · Issue #3809 · FasterXML/jackson-databind
March 5, 2023 - Currently with Jackson 2.x the only way to traverse entries of ObjectNode is using fields() method. This has the problem that it returns Iterator (of Map.Entry<String, JsonNode>) which is awkward to use (with Java 8 and above).
Author cowtowncoder
Jenkov
jenkov.com › tutorials › java-json › jackson-jsonnode.html
Jackson JsonNode
The Jackson JsonNode class is the Jackson tree object model for JSON. Jackson can read JSON into an object graph (tree) of JsonNode objects. Jackson can also write a JsonNode tree to JSON. This Jackson JsonNode tutorial explains how to work with the Jackson JsonNode class and its mutable subclass ...
Javatpoint
javatpoint.com › iterate-json-array-java
Iterate JSON Array Java - Javatpoint
Iterate JSON Array Java with java tutorial, features, history, variables, object, programs, operators, oops concept, array, string, map, math, methods, examples etc.
Red Hat
access.redhat.com › webassets › avalon › d › red-hat-jboss-enterprise-application-platform › 7.1.beta › javadocs › com › fasterxml › jackson › databind › JsonNode.html
JsonNode (Red Hat JBoss Enterprise Application Platform 7.1.0.Beta1 public API)
Same as calling elements(); implemented so that convenience "for-each" loop can be used for looping over elements of JSON Array constructs. ... 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 ...