How to create a Nested JSON Object payload and pass it as the payload of Playwright Java API post request.

Sameera De Silva
4 min readAug 15, 2023

--

Let’s warm up with an easy one , I want to create the below payload.

{
"monitors": [
{
"monitorId": "yourMonitorIdVariable"
}
]
}

For that I could use below code. Refer the inline comments for clarity. This will give the above outcome.

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;


public class JsonCreation {
public JsonObject jsonBodyCreationToExecuteSyntheticAlert(String monitorId) {





// Create the main JSON object
JsonObject mainJsonObjectPayload = new JsonObject();

// Create the "monitors" array
JsonArray monitorsArray = new JsonArray();

// Create a monitor object
JsonObject monitorObject = new JsonObject();
monitorObject.addProperty("monitorId", monitorId);

// Add the monitor object to the monitors array
monitorsArray.add(monitorObject);

// Add the monitors array to the main JSON object
mainJsonObjectPayload.add("monitors", monitorsArray);

return mainJsonObjectPayload;
}
}

If you get below error, Don’t use jsonObject.toString on a JSON object when use the Json object in the Rest assured payload.

{
"error": {
"code": 400,
"message": "Could not map JSON at '' near line 1 column 1"
}
}

To demonstrate this, I used the https://petstore.swagger.io/#/pet/addPet example. I want to generate this payload and pass it .

{
"id": 0,
"category": {
"id": 0,
"name": "string"
},
"name": "doggie",
"photoUrls": ["samurl"],
"tags": [{
"id": 666,
"name": "myname"
}],
"status": "available"
}

So let’s breakdown the generating the payload as a separate class.This will print the above payload.

package com.payloads;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class CreatedNestedJSONObjectPayloadUsingJavaMapWithArray {
public static void main(String[] args) {
// Create a Gson instance
Gson gson = new Gson();

// Create the main JSON object
JsonObject mainJsonObjectPayload = new JsonObject();

// Add properties to the main JSON object since id doesn't have child can add directly.

mainJsonObjectPayload.addProperty("id", 0);

// Create and add the nested "category" JSON object since category has two children as id,name
JsonObject categoryObject = new JsonObject();
categoryObject.addProperty("id", 0);
categoryObject.addProperty("name", "string");
//After that add category to main object as a simple key and value.
mainJsonObjectPayload.add("category", categoryObject);

// since id doesn't have child can add directly.
mainJsonObjectPayload.addProperty("name", "doggie");

// Create and add the "photoUrls" JSON array since "photoUrls" value is an array with 1 element.
JsonArray photoUrlsArray = new JsonArray();
// Add array element
photoUrlsArray.add("samurl");
//After that add photoUrls to main object as a simple key and value.
mainJsonObjectPayload.add("photoUrls", photoUrlsArray);

// Create and add the "tags" JSON array, tags also same , it has 2 elements as id and name.
JsonArray tagsArray = new JsonArray();
JsonObject tagObject = new JsonObject();
tagObject.addProperty("id", 666);
tagObject.addProperty("name", "myname");
tagsArray.add(tagObject);
mainJsonObjectPayload.add("tags", tagsArray);


// since id doesn't have child can add directly.
mainJsonObjectPayload.addProperty("status", "available");

// Convert the JSON object to a formatted string
String gsonOutput= gson.toJson(mainJsonObjectPayload);

// Print the formatted JSON output
System.out.println(gsonOutput);
}
}

So to create a pet we can use that

    //POST Call: create a user
APIResponse apiPostResponse = requestContext.post("https://petstore.swagger.io/v2/pet",
RequestOptions.create()
.setHeader("Content-Type", "application/json")
.setData(gsonOutput)
);

So all together the code is as per below.

package com.api.scripts;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.microsoft.playwright.APIRequest;
import com.microsoft.playwright.APIRequestContext;
import com.microsoft.playwright.APIResponse;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.options.RequestOptions;
import org.testng.Assert;
import org.testng.annotations.*;

import java.io.IOException;


public class PostNestedJsonObjectWithArray {
Playwright playwright;
APIRequest request;
APIRequestContext requestContext;

@BeforeClass
public void setup() {
playwright = Playwright.create();
request = playwright.request();
requestContext = request.newContext();
}




@Test
public void createUserTest() throws IOException {


// Create a Gson instance
Gson gson = new Gson();

// Create the main JSON object
JsonObject mainJsonObjectPayload = new JsonObject();

// Add properties to the main JSON object since id doesn't have child can add directly.

mainJsonObjectPayload.addProperty("id", 0);

// Create and add the nested "category" JSON object since category has two children as id,name
JsonObject categoryObject = new JsonObject();
categoryObject.addProperty("id", 0);
categoryObject.addProperty("name", "string");
//After that add category to main object as a simple key and value.
mainJsonObjectPayload.add("category", categoryObject);

// since id doesn't have child can add directly.
mainJsonObjectPayload.addProperty("name", "doggie");

// Create and add the "photoUrls" JSON array since "photoUrls" value is an array with 1 element.
JsonArray photoUrlsArray = new JsonArray();
// Add array element
photoUrlsArray.add("samurl");
//After that add photoUrls to main object as a simple key and value.
mainJsonObjectPayload.add("photoUrls", photoUrlsArray);

// Create and add the "tags" JSON array, tags also same , it has 2 elements as id and name.
JsonArray tagsArray = new JsonArray();
JsonObject tagObject = new JsonObject();
tagObject.addProperty("id", 666);
tagObject.addProperty("name", "myname");
tagsArray.add(tagObject);
mainJsonObjectPayload.add("tags", tagsArray);


// since id doesn't have child can add directly.
mainJsonObjectPayload.addProperty("status", "available");

// Convert the JSON object to a formatted string
String gsonOutput = gson.toJson(mainJsonObjectPayload);

// Print the formatted JSON output
System.out.println(gsonOutput);



//POST Call: create a user
APIResponse apiPostResponse = requestContext.post("https://petstore.swagger.io/v2/pet",
RequestOptions.create()
.setHeader("Content-Type", "application/json")
.setData(gsonOutput)
);

System.out.println(apiPostResponse.status());
Assert.assertEquals(apiPostResponse.status(), 200);

System.out.println(apiPostResponse.text());

ObjectMapper objectMapper = new ObjectMapper();
JsonNode postJsonResponse = objectMapper.readTree(apiPostResponse.body());
System.out.println(postJsonResponse.toPrettyString());

//capture id from the post json response:
String userId = postJsonResponse.get("id").asText();
System.out.println("user id : " + userId);


}
@AfterClass
public void tearDown() {
playwright.close();
}
}

This will generates the below output.

{"id":0,"category":{"id":0,"name":"string"},"name":"doggie","photoUrls":["samurl"],"tags":[{"id":666,"name":"myname"}],"status":"available"}
200
{"id":9223372036854755489,"category":{"id":0,"name":"string"},"name":"doggie","photoUrls":["samurl"],"tags":[{"id":666,"name":"myname"}],"status":"available"}
{
"id" : 9223372036854755489,
"category" : {
"id" : 0,
"name" : "string"
},
"name" : "doggie",
"photoUrls" : [ "samurl" ],
"tags" : [ {
"id" : 666,
"name" : "myname"
} ],
"status" : "available"
}
user id : 9223372036854755489

POM.XML that I used it as per below.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.example</groupId>
<artifactId>PlayrightMavenJavaDemo</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>18</maven.compiler.source>
<maven.compiler.target>18</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M1</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>mytestng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.8.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>1.33.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20230618</version>
</dependency>
</dependencies>
</project>

Some good videos to check about payload generation-https://www.youtube.com/watch?v=3USL0lolTtU&ab_channel=TalkwithLal

--

--

No responses yet