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
🌐
Readthedocs
jse.readthedocs.io › en › latest › utils › jackson › jacksonJsonNodeForEach.html
Jackson JsonNode.forEach() with Java 8 Consumer — Java Repositories 1.0 documentation
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); JacksonJsonNodeForEachTest ·
🌐
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&ltJsonNode&gt data = (JsonNode node) -&gt System.out.println(node.asText()); jsonNode.forEach(data); } } Find the output.
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.

🌐
Java2s
java2s.com › example › java-api › com › fasterxml › jackson › databind › jsonnode › foreach-1-0.html
Example usage for com.fasterxml.jackson.databind JsonNode forEach
default void forEach(Consumer<? super T> action) Source Link · Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. From source file:com.ibm.watson.catalyst.jumpqa.trec.TrecReader.java · private static List<String> ...
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
🌐
GitHub
github.com › Bunny83 › SimpleJSON › issues › 24
Example of using foreach on JSONNode ? · Issue #24 · Bunny83/SimpleJSON
February 17, 2019 - var UserSettings = JSON.Parse(json_string); // Merge UserSettings into DefaultSettings foreach ( var rootElement in UserSettings) { switch (rootElement.Key) { case "ClockType": AirSimSettings.GetSettings().ClockType = rootElement.Value; break; case "ClockSpeed": AirSimSettings.GetSettings().ClockSpeed = rootElement.Value.AsDouble; break; case "Recording": foreach (var sub1 in UserSettings["Recording"]) { switch (sub1.Key) { case "RecordOnMove": AirSimSettings.GetSettings().Recording.RecordOnMove = sub1.Value.AsBool; break; case "RecordInterval": AirSimSettings.GetSettings().Recording.RecordInt
Author: Bunny83
Find elsewhere
🌐
Medium
medium.com › @lakshmanaselvan252 › explain-about-the-jsonnode-and-arraynode-in-spring-boot-17f81c3de915
Explain About The JsonNode And ArrayNode In Spring Boot | by Lakshmana Selvan V | Medium
August 21, 2024 - ArrayNode is a subclass of JsonNode specifically designed to represent JSON arrays. It allows you to work with JSON arrays similarly to how you would work with List in Java. You can add, remove, and retrieve elements from the array. ... Array-Specific Operations: Methods like add(), insert(), remove(), and set() allow you to manipulate the elements of the array. Iterating: You can iterate over the elements of an ArrayNode using a for loop or forEach.
Top answer
1 of 3
13

You are parsing the JSON when Jackson is meant to do it for you. Don't do this to yourself.

One option is to create a DTO (Data Transfer Object) that matches the format of your JSON

class Root {
    private String message;
    private String cod;
    private int count;
    private List<City> list;
    // appropriately named getters and setters
}

class City {
    private long id;
    private String name;
    private Coordinates coord;
    private List<Weather> weather;
    // appropriately named getters and setters
}

class Coordinates {
    private double lon;
    private double lat;
    // appropriately named getters and setters
}

class Weather {
    private int id;
    private String main;
    private String description;
    private int temp;
    // appropriately named getters and setters
}

Then use an ObjectMapper and deserialize the root of the JSON.

ObjectMapper mapper = new ObjectMapper();
Root root = mapper.readValue(yourFileInputStream, Root.class);

You can then get the field you want. For example

System.out.println(root.getList().get(0).getWeather().get(0).getTemp());

prints

74

The alternative is to read your JSON in as a JsonNode and traverse it until you get the JSON element you want. For example

JsonNode node = mapper.readTree(new File("text.json"));
System.out.println(node.get("list").get(0).get("weather").get(0).get("temp").asText());

also prints

74
2 of 3
3

Based on the answer that Sotirios Delimanolis gave me, here was my solution:

ObjectMapper mapper = new ObjectMapper();
JsonFactory jfactory = mapper.getFactory();
JsonParser jParser;
try {
    jParser = jfactory.createParser( tFile );
    JsonNode node = mapper.readTree( jParser);
    int count = node.get("count").asInt();
    for ( int i = 0; i < count; i++ ) {
     System.out.print( "City: " + node.get("list").get(i).get("name").asText() );
        System.out.println( " , Absolute temperature: " + 
            node.get("list").get(i).get("main").get("temp").asText() );
    }
    jParser.close();
} catch (IOException e) {
    e.printStackTrace();
}
🌐
GitHub
gist.github.com › seayxu › bf4f81988489a4d65144b92e1d0224cf
C# foreach json node function by Newtonsoft.Json · GitHub
April 8, 2016 - C# foreach json node function by Newtonsoft.Json. GitHub Gist: instantly share code, notes, and snippets.
🌐
Java Code Geeks
javacodegeeks.com › home › enterprise java
Simplified Json Array Operations with JsonNode in Jackson
May 6, 2024 - ArrayNode arrayNode = (ArrayNode) rootNode.get("myArray"); StreamSupport.stream(arrayNode.spliterator(), false) .forEach(element -> System.out.println(element.asText())); This method allows for convenient streaming and processing of JSON array elements. Iterating over elements in a JSON array without typecasting can be achieved using an Iterator: ArrayNode arrayNode = (ArrayNode) rootNode.get("myArray"); Iterator<JsonNode> elements = arrayNode.elements(); while (elements.hasNext()) { JsonNode element = elements.next(); // Process each element }
🌐
Medium
medium.com › @reham.muzzamil_67114 › a-quick-guide-to-iterate-over-a-dynamic-json-string-6b024aa6b1e
A quick guide to Iterate over a dynamic JSON string! | by Reham Muzzamil | Medium
May 16, 2020 - public JsonNode traverse(JsonNode node) {s if (node.isValueNode()) { if (JsonNodeType.STRING == node.getNodeType()) { return JsonNodeFactory.instance.textNode( StringUtils.encodeValue(node.asText())); // You can use any other encoding function ...
🌐
GitHub
gist.github.com › 38f207816554b8bbffef58aa7cfebcf1
How to iterate over a Jackon JsonNode / Java Map Entry iterator in Scala · GitHub
And if we have an array in the JSON, it will be not JsonNode, but ArrayNode. To iterate it, use elements instead of fields o.elements.asScala ... Also asScala creates a Scala-like collection which can be chained with .foreach, .map, etc.
🌐
Stack Overflow
stackoverflow.com › questions › 69647101 › how-can-we-iterate-all-subnodes-of-a-jsonnode-object
java - How can we iterate all subNodes of a jsonNode object? - Stack Overflow
ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(response); JsonNode itemsNode = root.get("content") .get("cart") .get("logs") .get("logs_cart_100") .get("items"); Iterator<Map.Entry<String, JsonNode>> nodesIterator = itemsNode.fields(); Stream<Map.Entry<String, JsonNode>> nodesStream = StreamSupport.stream( Spliterators.spliteratorUnknownSize(nodesIterator, 0), false); Map<String, Item> items = nodesStream.collect( Collectors.toMap(Map.Entry::getKey, node -> Item.ofJsonNode(node.getValue()))); items.forEach((id, item) -> System.out.println(id + ": " + item)); Output: 111: [firstName=Ram, lastName=K, price=[amount=100.0, baseAmount=100.0]] 222: [firstName=Velvan, lastName=S, price=[amount=200.0, baseAmount=200.0]] 333: [firstName=Dinesh, lastName=M, price=[amount=300.0, baseAmount=300.0]] Share ·
🌐
Fasterxml
fasterxml.github.io › jackson-databind › javadoc › 2.9 › com › fasterxml › jackson › databind › JsonNode.html
JsonNode (jackson-databind 2.9.0 API)
forEach, spliterator · serialize, serializeWithType · protected JsonNode() public abstract <T extends JsonNode> T deepCopy() Method that can be called to get a node that is guaranteed not to allow changing of this node through mutators on this node or any of its children.