Compare with name and update that json element.

Resource resource = new ClassPathResource("gateway-fields.json");  //read from json file
      JsonFactory jsonFactory = new JsonFactory();
      ObjectMapper objectMapper = new ObjectMapper(jsonFactory);

      JsonNode arrayNode = objectMapper.readTree(resource.getFile()).get("fields");

      if (arrayNode.isArray()) {
          for (JsonNode jsonNode : arrayNode) {
              String nameFieldNode = jsonNode.get("name").asText();    
              if("RefNo".equals(nameFieldNode)){
                     ((ObjectNode)jsonNode).put("name", "1112");
              }
          }
      }
Answer from Kaustubh Khare on Stack Overflow
🌐
Baeldung
baeldung.com › home › json › jackson › simplified array operations on jsonnode without typecasting in jackson
Simplified Array Operations on JsonNode Without Typecasting in Jackson | Baeldung
June 27, 2025 - This approach reduces the overall complexity by directly iterating through the elements. It provides a straightforward mechanism for customizing the processing of JSON elements during iteration. In this tutorial, we explored various approaches to simplifying array operations on JsonNode without explicitly typecasting it to ArrayNode in Jackson.
🌐
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 - ... 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.
🌐
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.
🌐
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 - 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\",\"state\":\"France\"}}"; JsonNode jsonNode = objectMapper.readTree(json); Iterator<Map.entry<String, JsonNode>> fields = jsonNode.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> field = fields.next(); System.out.println("Field name: " + field.getKey()); System.out.println("Field value: " + field.getValue()); System.out.println("###################"); } } }
🌐
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.
🌐
Oracle
docs.oracle.com › en › applications › jd-edwards › development-tools › 9.2.x › eotjc › example-using-jackson-libraries-to-iterate-through-rows-and-get.html
Example - Using Jackson Libraries to Iterate Through Rows and Get Values
January 16, 2023 - Example - Using Jackson Libraries to Iterate Through Rows and Get Values · JsonNode node = loginEnv.getObjectMapper().readTree(response); JsonNode array = node.path("fs_DATABROWSE_F0101").path("data").path("gridData").path("rowset"); for (Iterator<JsonNode> rows = array.iterator(); rows.hasNext();) { JsonNode aRow = rows.next(); System.out.println("Name: " +aRow.get("F0101_ALPH")); }
🌐
Tabnine
tabnine.com › home page › code › java › com.fasterxml.jackson.databind.jsonnode
com.fasterxml.jackson.databind.JsonNode.forEach java code examples | Tabnine
private HashMap<String, String> getObjectHrefs(JsonNode objectNode) { HashMap<String, String> result = new LinkedHashMap<>(); JsonNode linksNode = objectNode.get("_links"); Iterator<String> names = linksNode.fieldNames(); linksNode.forEach(node -> result.put(names.next(), node.get("href").toString().replace("\"", ""))); return result; }
Find elsewhere
🌐
GitHub
github.com › FasterXML › jackson-databind › issues › 3120
Return `ListIterator` from `ArrayNode.elements()` · Issue #3120 · FasterXML/jackson-databind
April 16, 2021 - Proposed Solution A possible solution would be to internally use the ListIterator instead of an Iterator when calling ArrayNode.elements(). With a ListIterator, it is possible to cast the iterator to ListIterator and then call iterator.set(JsonNode value):
Author   ludgerb
🌐
Jenkov
jenkov.com › tutorials › java-json › jackson-jsonnode.html
Jackson JsonNode
A JsonNode that represents a JSON object or JSON array can be traversed like any other object graph. You do so by iterating its nested fields (or nested elements in case of an array).
🌐
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 - } else if (JsonNodeType.NULL == node.getNodeType()) { return null; } else { return node; } } else if (node.isNull()) { return null; } else if (node.isArray()) { ArrayNode arrayNode = (ArrayNode) node; ArrayNode cleanedNewArrayNode = mapper.createArrayNode(); for (JsonNode jsonNode : arrayNode) { cleanedNewArrayNode.add(traverse(jsonNode)); } return cleanedNewArrayNode; } else { ObjectNode encodedObjectNode = mapper.createObjectNode(); for (Iterator<Map.Entry<String, JsonNode>> it = node.fields(); it.hasNext(); ) { Map.Entry<String, JsonNode> entry = it.next(); encodedObjectNode.set(StringUtils.encodeValue(entry.getKey()), traverse(entry.getValue())); } return encodedObjectNode; } }
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.

🌐
ConcretePage
concretepage.com › jackson-api › jackson-jsonnode-foreach-with-java-8-consumer
Jackson JsonNode.forEach() with Java 8 Consumer
March 2, 2015 - Jackson API 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.
🌐
Tabnine
tabnine.com › home page › code › java › com.fasterxml.jackson.databind.node.arraynode
com.fasterxml.jackson.databind.node.ArrayNode.iterator java code examples | Tabnine
public static List<JsonNode> getAppModelReferencedProcessModels(JsonNode appModelJson) { List<JsonNode> result = new ArrayList<>(); if (appModelJson.has("models")) { ArrayNode modelsArrayNode = (ArrayNode) appModelJson.get("models"); Iterator<JsonNode> modelArrayIterator = modelsArrayNode.iterator(); while (modelArrayIterator.hasNext()) { result.add(modelArrayIterator.next()); } } return result; } ... public static List<JsonNode> getAppModelReferencedProcessModels(JsonNode appModelJson) { List<JsonNode> result = new ArrayList<JsonNode>(); if (appModelJson.has("models")) { ArrayNode modelsArrayNode = (ArrayNode) appModelJson.get("models"); Iterator<JsonNode> modelArrayIterator = modelsArrayNode.iterator(); while (modelArrayIterator.hasNext()) { result.add(modelArrayIterator.next()); } } return result; }
🌐
Baeldung
baeldung.com › home › json › jackson › working with tree model nodes in jackson
Working with Tree Model Nodes in Jackson | Baeldung
January 8, 2024 - Next, let’s look at an Array node. Each item within the Array node is itself a JsonNode, so we iterate over the Array and pass each node to the appendNodeToYaml method.
🌐
Fasterxml
fasterxml.github.io › jackson-databind › javadoc › 2.6 › com › fasterxml › jackson › databind › node › ArrayNode.html
ArrayNode (jackson-databind 2.6.0 API)
For array nodes, index specifies exact location within array and allows for efficient iteration over child elements (underlying storage is guaranteed to be efficiently indexable, i.e. has random-access to elements).
🌐
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
🌐
Fasterxml
fasterxml.github.io › jackson-databind › javadoc › 2.7 › com › fasterxml › jackson › databind › JsonNode.html
JsonNode (jackson-databind 2.7.0 API)
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. public Iterator<Map.Entry<String,JsonNode>> fields()