Make Selenium Easy

REST Assured Tutorial 43 – Get All Keys From A Nested JSON Object

Introduction

We may get a nested JSON Object which may be dynamic. The dynamic response may include conditional keys and values. For example- A business class ticket will have more benefits than an economy class ticket. If we have an API that books a ticket then obviously we will have different JSON (Suppose JSON as format) response. The same may apply for the JSON request body as well.

In short, you may need to get all keys from a normal JSON object and nested JSON object. This is an interview question as well. You may be asked just to check the presence of a key in JSON response.

Prerequisite

Required Java Library

Since we are using Jackson API of Java for this example, make sure you have the latest dependency of Jackson Databind in your project classpath. I have used below Jackson dependency for this post:-

Simple JSON Object

Example JSON Object

Using Java MAP

As we know that we can deserialize a JSON Object to Java Map easily. As Map is a key-value pair we can get all keys easily.

Output

Using JsonNode

We need to use a method “readTree()” provided by “ObjectMapper” class which is overloaded. Method “readTree()” is to deserialize JSON content as tree expressed using a set of JsonNode instances. JsonNode is a base class for all JSON nodes, which form the basis of the JSON Tree Model that Jackson implements. One way to think of these nodes is to consider them similar to DOM nodes in XML DOM trees. Source – Jackson Java Doc

Output

Nested JSON Object

Example JSON Object

If we use the above logic to get keys from the nested JSON object we will not get keys “city” and “state”. So here we need to put extra logic to check if the value of a key is a JSON Object. If yes then we need to get keys from that as well.

Using Map

When we deserialize a JSON Objects to Map then it is actually an instance of LinkedHashMap. We can use LinkedHashMap directly instead of Map.

Output

Using JsonNode

Output

You can download/clone the above sample project from here.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappyLearning

Find all Selenium related posts here, all API manual and automation related posts here, and find frequently asked Java Programs here.

Many other topics you can navigate through the menu.

Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.