top of page

How to traverse a Json tree and how to find and extract nested elements in Json?

Updated: Sep 12, 2021

Micro services communicate with each other using RESTful APIs. The response often is a nested Json. If we want to represent the nested json as a pure object then we need a model of the json which will result in a nested object structure. Often the nested object structure is not required; we just need to find and extract a part of an inner element in the json tree. In this post I will show you how we can traverse a Json tree structure and how we can find and extract an element from the tree.


Let's assume the json tree look like this

{
    "ParentElement1": [{
            "Name": "",
            "Description": "",
            "Id": "",
            },
            "BaseEmement1": [],
            "BaseEmement2": [],
            "BaseEmement3": [[{
                        "ChildEmement1": "InvalidCell"
                    }
                ]],
            "BaseEmement4": [],
            "BaseEmement5": 0,
            "BaseEmement6": false,
            "Messages": [{
                    "Type": 1,
                    "Text": "my search text"
                }
            ]
    }],
    "ParentElement2": {
        "Timestamp": "2020-10-27 19:13:04.8800000",
    }
}

We will use Json ObjectMapper to read and traverse this json.

The code for this is shown below

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
 
jsonString =  "<string format of the above json>";
ObjectMapper parser =new ObjectMapper();
try {
JsonNode jsonNode = parser.readTree(jsonString);
if(!JsonNode.has("ParentElement1")) {
return false;
  }
  JsonNode grids = jsonNode.get("ParentElement1");
  for( JsonNode node: grids) {
   if(node.has("Messages")) {
    JsonNode messages = node.get("Messages");
    String text = messages.get(0).get("Text").textValue();
    if(text.contains("my search text")) {
     return true;
     }
   }
  }
  return false;
} catch(Exception e) {
  logger.error("Could not parse {}", e.getMessage());
}

Recent Posts

See All
bottom of page