REST Assured: Creating Nested JSON Object Payload Using Java Map

Profile picture for user arilio666

When worked on, there might come a time when we want to use nested JSON payload.
So what is it?

{
 "id": "002",
 "First_Name": "John",
 "Last_Name": "Wick",
 "Profession": "Assassin",
 "Contracts": {
   "Target_One": "Vincenzo",
   "Target_Two": "Winston",
   "Target_Three": "Diane"
 }
}
  • Upto the point of profession property in JSON, it is normal.
  • Contracts have another JSON nested within them that contains three more properties.

In this article, we will see how to create a nested JSON using a java map, and rest assured.

package week4.day2;
import java.util.LinkedHashMap;
import java.util.Map;
import io.restassured.RestAssured;
public class Nested {
    public static void main(String[] args) {
        Map<String, Object> payload = new LinkedHashMap<>();
        payload.put("id", "002");
        payload.put("First_Name", "John");
        payload.put("Last_Name", "Wick");
        payload.put("Profession", "Assassin");

    }
}
  • This is the first part of the problem, where we have created a payload object for the java map.
  • Then simply using put, we add the desired JSON data to the normal part profession.
Map<String, Object> targetsMap = new LinkedHashMap<String, Object>();
        targetsMap.put("Target_One", "Vincenzo");
        targetsMap.put("Target_Two", "Winston");
        targetsMap.put("Target_Three", "Diane");
  •         
    Then we create another hashmap and add in the nested JSON.
package week4.day2;
import java.util.LinkedHashMap;
import java.util.Map;
import io.restassured.RestAssured;
public class Nested {
    public static void main(String[] args) {
        Map<String, Object> payload = new LinkedHashMap<>();
        payload.put("id", "002");
        payload.put("First_Name", "John");
        payload.put("Last_Name", "Wick");
        payload.put("Profession", "Assassin");
        Map<String, Object> targetsMap = new LinkedHashMap<String, Object>();
        targetsMap.put("Target_One", "Vincenzo");
        targetsMap.put("Target_Two", "Winston");
        targetsMap.put("Target_Three", "Diane");
        payload.put("Contracts", targetsMap);
        RestAssured.given().log().all().body(payload).get();
    }
}
  • In the end, we create nested JSONs property contracts using the old hashmap object and place the second hashmap.
  • This assigns the data to it.
  • We can see the JSON body it created and logged using rest assured.
  • This is the final result of the hashmap operation when pasted onto the online JSON editor.
  • We got the desired input.

Conclusion:
This is how we can create nested JSON using java map.