Iterate over JsonNode in Java

In this lesson, you will learn how to iterate over JsonNode in Java.  JsonNode class is the base class for all JSON nodes, which form the basis of Jackson’s JSON Tree Model.

How to iterate over JsonNode in Java?

To loop through the JsonNode, we need to use the Java Iterator interface. 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\",\"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("###################");
    }
  }
}
Output: Field name: key1 Field value: “value1” ################### Field name: user Field value: {“name”:”Steve”,”city”:”Paris”,”state”:”France”} ###################
 
If you want to learn other things you can do with Jackson in Java, check out the main Java JSON tutorial.
 
Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *