REST Assured Tutorial 46 – Fetch Value From JSON Array Using JsonNode – Jackson – Get() & Path() Methods

Introduction

As a part of End to End REST Assured Tutorial, in this post, we will parse a JSON Array as JsonNode to fetch values of different types.

Creating POJO classes for parsing a JSON to fetch values may not be easy all the time especially when you have lengthy nested JSON and dynamic JSON. Instead, we can use the tree structure of a JSON so that we can navigate to any node via a path.

Prerequisite

We have already covered parsing a simple JSON Object and a Nested JSON Object as JsonNode previously. You must refer those posts to understand parsing JSON array well.

Fetch Value From JSON Object Using JsonNode

Fetch Value From Nested JSON Object Using JsonNode

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:-



    com.fasterxml.jackson.core
    jackson-databind
    2.11.1

Tree representation of JSON Array

Example JSON Array

Tree representation of JSON Array

You can use this site to view the tree representation of a JSON Array. A tree representation of the above example JSON array will look as below:-

A JSON array may be a collection of JSON objects or JSON arrays. Below is also a valid example of a JSON array.

[
  [
    {
      "firstName": "Amod",
      "lastName": "Mahajan",
      "age": 28,
      "isMarried": false,
      "salary": 23456.54
    },
    {
      "firstName": "Rahul",
      "lastName": "Arora",
      "age": 32,
      "isMarried": true,
      "salary": 33456.54
    }
  ],
  [
    {
      "firstName": "Amod",
      "lastName": "Mahajan",
      "age": 28,
      "isMarried": false,
      "salary": 23456.54
    },
    {
      "firstName": "Rahul",
      "lastName": "Arora",
      "age": 32,
      "isMarried": true,
      "salary": 33456.54
    }
  ]
]

Deserialize a JSON Array to Tree

We need to use class ObjectMapper provided by Jackson API. ObjectMapper class provides a method “readTree()” which is responsible to deserialize JSON content as tree expressed using a set of JsonNode instances.

We can get the value of a node using get() and path() methods of JsonNode class. We need to extract value with appropriate data types after using get() and path() methods.

We just need to use an index to fetch an element of an array which is the core concept of an array.

// Creating an instance of ObjectMapper class
ObjectMapper objectMapper = new ObjectMapper();
// Get tree representation of json
JsonNode jsonTree = objectMapper.readTree(jsonArray);
		
// Get first json object and storing 
JsonNode firstJsonObject = jsonTree.get(0);
// Get second json object and storing 
JsonNode secondJsonObject = jsonTree.get(1);

If you are not sure if parsed JSON tree is a JSON object or JSON tree then you can use instanceof as below:-

// To know if tree is a JSON object or JSON array
System.out.println("Is parsed JSOn tree a JSON Object?"+ Boolean.toString(jsonTree instanceof ObjectNode));
System.out.println("Is parsed JSOn tree a JSON Array?"+ Boolean.toString(jsonTree instanceof ArrayNode));

Remember that JsonNode is the parent class of both ObjectNode and ArrayNode.

Remaining all concepts are the same as we discussed in the posts mentioned under prerequisite headers. If you are sure of if JSON is an object or array we can directly cast and store in that type.

ArrayNode jsonTree = (ArrayNode) objectMapper.readTree(jsonArray);

Example Program

package JsonNodeJackson;

import org.testng.annotations.Test;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class ParseJsonArrayToReadValues {
	
	@Test
	public void parseJsonArrayToReadValues() throws JsonMappingException, JsonProcessingException
	{
		String jsonArray = "[\r\n" + 
				"  {\r\n" + 
				"    \"firstName\": \"Amod\",\r\n" + 
				"    \"lastName\": \"Mahajan\",\r\n" + 
				"    \"age\": 28,\r\n" + 
				"    \"isMarried\": false,\r\n" + 
				"    \"salary\": 23456.54\r\n" + 
				"  },\r\n" + 
				"  {\r\n" + 
				"    \"firstName\": \"Rahul\",\r\n" + 
				"    \"lastName\": \"Arora\",\r\n" + 
				"    \"age\": 32,\r\n" + 
				"    \"isMarried\": true,\r\n" + 
				"    \"salary\": 33456.54\r\n" + 
				"  }\r\n" + 
				"]";
		
		
		// Creating an instance of ObjectMapper class
		ObjectMapper objectMapper = new ObjectMapper();
		// Get tree representation of json
		JsonNode jsonTree = objectMapper.readTree(jsonArray);
		
		// To know if tree is a JSON object or JSON array
		System.out.println("Is parsed JSOn tree a JSON Object?"+ Boolean.toString(jsonTree instanceof ObjectNode));
		System.out.println("Is parsed JSOn tree a JSON Array?"+ Boolean.toString(jsonTree instanceof ArrayNode));
		
		// Get first json object and storing 
		JsonNode firstJsonObject = jsonTree.get(0);
		// Get second json object and storing 
		JsonNode secondJsonObject = jsonTree.get(1);
		
		// Get value of firstName as string
		String firstName = firstJsonObject.get("firstName").asText();
		String lastName = firstJsonObject.get("lastName").asText();
		// Get value of married as boolean
		int age = firstJsonObject.get("age").asInt();
		boolean married = firstJsonObject.get("isMarried").asBoolean();
		double salary = firstJsonObject.get("salary").asLong();
		
		System.out.println("FirstName is : "+firstName);
		System.out.println("LastName is  : "+lastName);
		System.out.println("Age is   : "+age);
		System.out.println("Maritial status is    : "+married);
		System.out.println("Salary is: "+salary);
		
		
		// Get value of firstName as string
		firstName = secondJsonObject.get("firstName").asText();
		lastName = secondJsonObject.get("lastName").asText();
		// Get value of married as boolean
		age = secondJsonObject.get("age").asInt();
		married = secondJsonObject.get("isMarried").asBoolean();
		salary = secondJsonObject.get("salary").asLong();
		
		System.out.println("FirstName is : "+firstName);
		System.out.println("LastName is  : "+lastName);
		System.out.println("Age is   : "+age);
		System.out.println("Maritial status is    : "+married);
		System.out.println("Salary is: "+salary);
				
	}

}
Output
Is parsed JSOn tree a JSON Object?false
Is parsed JSOn tree a JSON Array?true
FirstName is : Amod
LastName is  : Mahajan
Age is   : 28
Maritial status is    : false
Salary is: 23456.0
FirstName is : Rahul
LastName is  : Arora
Age is   : 32
Maritial status is    : true
Salary is: 33456.0

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.

Leave a Reply

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