</>

Technology

Rest Assured

Difficulty

Intermediate

Interview Question

How to send a nested JSON object as payload in Rest Assured?

Answer

Sending Nested JSON Payload in Rest Assured

Method 1: Using HashMap (Most Common)

Target JSON:

JSON
{
  "space": {
    "name": "myspace",
    "id": "bishnu"
  }
}

Java Code:

Java
import java.util.HashMap;

@Test
public void sendNestedJsonPayload() {

    HashMap<String, Object> mainObj = new HashMap<String, Object>();
    HashMap<String, String> subObj = new HashMap<String, String>();

    subObj.put("name", "QA");
    subObj.put("id", "bishnu");
    mainObj.put("space", subObj);

    Response resp = given()
                        .contentType(ContentType.JSON)
                        .body(mainObj)
                        .when()
                        .post("https://api.example.com/spaces");

    assertEquals(resp.getStatusCode(), 201);
}

Method 2: Using POJO with Nested Class

Java
// Inner POJO
public class Space {
    private String name;
    private String id;
    // getters/setters
}

// Outer POJO
public class SpaceRequest {
    private Space space;
    // getters/setters
}

@Test
public void sendNestedWithPOJO() {
    Space space = new Space();
    space.setName("myspace");
    space.setId("bishnu");

    SpaceRequest request = new SpaceRequest();
    request.setSpace(space);

    given()
        .contentType(ContentType.JSON)
        .body(request)
        .when()
        .post("/api/spaces")
        .then()
        .statusCode(201);
}

Method 3: Using JSONObject

Java
import org.json.JSONObject;

@Test
public void sendNestedWithJSONObject() {
    JSONObject subObj = new JSONObject();
    subObj.put("name", "myspace");
    subObj.put("id", "bishnu");

    JSONObject mainObj = new JSONObject();
    mainObj.put("space", subObj);

    given()
        .contentType(ContentType.JSON)
        .body(mainObj.toString())
        .when()
        .post("/api/spaces")
        .then()
        .statusCode(201);
}

Method 4: Inline String

Java
String body = """
    {
        "space": {
            "name": "myspace",
            "id": "bishnu"
        }
    }
    """;

given().body(body).contentType(ContentType.JSON).when().post("/api/spaces").then().statusCode(201);

Follow AutomateQA

Related Topics