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
🌐
GitHub
github.com › FasterXML › jackson-databind › issues › 3120
Return `ListIterator` from `ArrayNode.elements()` · Issue #3120 · FasterXML/jackson-databind
April 16, 2021 - So the approach is, to traverse over the ObjectNode/ArrayNodes using the iterators provided via fields() (ObjectNode) respective elements() (ArrayNode).
Author   ludgerb
🌐
Tabnine
tabnine.com › home page › code › java › com.fasterxml.jackson.databind.node.arraynode
com.fasterxml.jackson.databind.node.ArrayNode.iterator java code examples | Tabnine
@Override public List deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { ObjectMapper mapper = (ObjectMapper) jp.getCodec(); JsonNode node = mapper.readTree(jp); List<Object> result = new ArrayList<Object>(); if (node != null) { if (node instanceof ArrayNode) { ArrayNode arrayNode = (ArrayNode) node; Iterator<JsonNode> nodeIterator = arrayNode.iterator(); while (nodeIterator.hasNext()) { JsonNode elementNode = nodeIterator.next(); result.add(mapper.readValue(elementNode.traverse(mapper), Object.class)); } } else { result.add(mapper.readValue(node.traverse(mapper), Object.class)); } } return Collections.unmodifiableList(result); } }
🌐
Fasterxml
fasterxml.github.io › jackson-databind › javadoc › 2.6 › com › fasterxml › jackson › databind › node › ArrayNode.html
ArrayNode (jackson-databind 2.6.0 API)
size in class ContainerNode<ArrayNode> public Iterator<JsonNode> elements() Description copied from class: JsonNode · 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.
🌐
Java Tips
javatips.net › api › com.fasterxml.jackson.databind.node.arraynode
Java Examples for com.fasterxml.jackson.databind.node.ArrayNode
*/ protected ObjectNode grantAnyoneAccess(ObjectNode node) { ObjectNode schema = (ObjectNode) node.get("schema"); ObjectNode access = (ObjectNode) schema.get("access"); Iterator<JsonNode> children = access.iterator(); while (children.hasNext()) { ArrayNode child = (ArrayNode) children.next(); child.removeAll(); child.add("anyone"); } return node; }
🌐
Program Creek
programcreek.com › java-api-examples
com.fasterxml.jackson.databind.node.ArrayNode#iterator
public static boolean arrayNodeContains(ArrayNode arrayNode, Object value) { Iterator<JsonNode> iterator = arrayNode.iterator(); while (iterator.hasNext()) { JsonNode jsonNode = iterator.next(); if (value == null && jsonNode.isNull()) { return true; } else if (value != null) { if (value instanceof String && jsonNode.isTextual() && StringUtils.equals(jsonNode.asText(), (String) value)) { return true; } else if (value instanceof Number && jsonNode.isLong() && jsonNode.longValue() == ((Number) value).longValue()) { return true; } else if (value instanceof Number && jsonNode.isDouble() && jsonNode
🌐
GitHub
github.com › FasterXML › jackson-databind › issues › 301
ArrayNode instance method fields() allways returns an empty iterator · Issue #301 · FasterXML/jackson-databind
September 5, 2013 - If you call the method fields() at ArrayNode instance it calls the method of the abstract supercalss JsonNode, which allways returns an empty iterator. It should return an iterator with all its children.
Author   dennisstritzke
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.

Find elsewhere
🌐
Adobe Developer
developer.adobe.com › experience-manager › reference-materials › cloud-service › javadoc › com › fasterxml › jackson › databind › node › ArrayNode.html
ArrayNode (The Adobe Experience Manager SDK 2022.11.9850.20221116T162329Z-220900)
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.
🌐
Fasterxml
fasterxml.github.io › jackson-core › javadoc › 1.9 › org › codehaus › jackson › node › ArrayNode.html
ArrayNode (Jackson JSON Processor)
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.
🌐
Tabnine
tabnine.com › home page › code › java › com.fasterxml.jackson.databind.node.arraynode
com.fasterxml.jackson.databind.node.ArrayNode.forEach java code examples | Tabnine
iterator · toString · addNull · Method that will add a null value at the end of this array node. remove · Method for removing an entry from this ArrayNode. Will return value of the entry at specified index, addNull, remove, insert, arrayNode, ...
🌐
Java Tips
javatips.net › api › org.codehaus.jackson.node.arraynode
Java Examples for org.codehaus.jackson.node.ArrayNode
*/ private static Attribute createConfigAttribute(final MBeanAttributeInfo attrib, final JsonNode node) throws ConfigException { String attribName = attrib.getName(); ObjectMapper mapper = new ObjectMapper(); ObjectNode rootNode = mapper.createObjectNode(); ArrayNode newSets = mapper.createArrayNode(); if (null != node.get(attribName)) { rootNode.put(attribName, node.get(attribName)); } if (null != node.get(SETS_TYPE)) { rootNode.put(SETS_TYPE, node.get(SETS_TYPE)); JsonNode origSets = node.get(SETS); if ((origSets != null) && origSets.isArray()) { Iterator&lt;JsonNode> itr = origSets.iterator
🌐
Fasterxml
fasterxml.github.io › jackson-databind › javadoc › 2.7 › com › fasterxml › jackson › databind › node › ArrayNode.html
ArrayNode (jackson-databind 2.7.0 API)
size in class ContainerNode<ArrayNode> public Iterator<JsonNode> elements() Description copied from class: JsonNode · 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.
🌐
Java Code Geeks
javacodegeeks.com › home › enterprise java
Simplified Json Array Operations with JsonNode in Jackson
May 6, 2024 - We’ll explore various methods like get(), createArrayNode(), and techniques involving Java’s StreamSupport and Iterator to streamline JSON array handling. Let’s dive into these methods step by step to enhance your JSON manipulation skills in Java. Jackson is a popular Java library used for JSON processing. JsonNode is a fundamental abstraction representing a node in the JSON tree structure, capable of representing various JSON types such as objects, arrays, strings, numbers, and more. 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.
🌐
javathinking
javathinking.com › blog › convert-arraynode-to-list-java
Converting ArrayNode to List in Java — javathinking.com
It represents an ordered collection of elements that can contain duplicates. Common implementations of the List interface include ArrayList and LinkedList. Converting an ArrayNode to a List allows you to perform operations like sorting, searching, ...
Top answer
1 of 2
5

Assuming that a row is one of the entries in a ArrayNode the following simple approach may be useful. It uses the JsonNode abstraction instead of a series of nested Map objects which I personally prefer since JsonNode provides a series of utility methods that are helpful when dealing with this kind of data (data where the structure is possibly unknown or very dynamic so that it can't be easily transformed to a POJO).

The testcase below illustrates how to find the number of rows and how to print the values. To get hold of the values the method JsonNode.elements() is used and the number of rows is simply a call to the size()-method.

public class ArrayNodeTest {
    @Test
    public void verifySizeAndPrintRows() throws IOException {
        final String jsonStr =
                "[{\"key11\":\"value11\",\"key12\":\"value12\"},\n" +
                        "{\"key21\":\"value21\",\"key22\":\"value22\"},\n" +
                        "{\"keyn1\":\"valuen1\",\"keyn2\":\"valuen2\"}]";

        final ObjectMapper mapper = new ObjectMapper();
        final JsonNode jsonNode = mapper.readTree(jsonStr);

        // Verify size
        Assert.assertEquals(3, jsonNode.size());

        // And print rows
        for (final JsonNode row : jsonNode) {
            final Iterable<JsonNode> iterable = () -> row.elements();
            iterable.forEach(elem -> System.out.println(elem.asText()));
        }
    }
}
2 of 2
0

to identify the number of rows

What's a "row"? Is a key/value pair a row? Is an element of the JSON array (no matter how many key/value pairs it contains) a row?

print only the values on the screen

Jackson has nothing to do with printing anything on any screens. Jackson can be used to populate a Java data structure from the input JSON, and the populated Java data structure can then be used however you want.

Given the JSON structure in the original question, a simple solution would be to bind to a list (or array) of maps, and then just iterate through the list of maps, accessing all of the values. Following is such an example.

import java.io.File;
import java.util.Map;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonFoo
{
  public static void main(String[] args) throws Exception
  {
    ObjectMapper mapper = new ObjectMapper();
    Map<String, String>[] maps = mapper.readValue(new File("input.json"), Map[].class);
    for (Map<String, String> map : maps)
    {
      for (Map.Entry<String, String> entry : map.entrySet())
      {
        System.out.println(entry.getValue());
      }
    }
  }
}

Output:

value11
value12
value21
value22
valuen1
valuen2
Top answer
1 of 3
89

Acquire an ObjectReader with ObjectMapper#readerFor(TypeReference) using a TypeReference describing the typed collection you want. Then use ObjectReader#readValue(JsonNode) to parse the JsonNode (presumably an ArrayNode).

For example, to get a List<String> out of a JSON array containing only JSON strings

CopyObjectMapper mapper = new ObjectMapper();
// example JsonNode
JsonNode arrayNode = mapper.createArrayNode().add("one").add("two");
// acquire reader for the right type
ObjectReader reader = mapper.readerFor(new TypeReference<List<String>>() {
});
// use it
List<String> list = reader.readValue(arrayNode);
2 of 3
13

If an Iterator is more useful...

...you can also use the elements() method of ArrayNode. Example see below.

sample.json

Copy{
    "first": [
        "Some string ...",
        "Some string ..."
    ],
    "second": [
        "Some string ..."
    ]
}

So, the List<String> is inside one of the JsonNodes.

Java

When you convert that inner node to an ArrayNode you can use the elements() method, which returns an Iterator of JsonNodes.

CopyFile 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