How to post nested json in restassured

3.5k views Asked by At

Below is the code I am using

JSONObject requestParams = new JSONObject();
requestParams.put("something", "something value");
requestParams.put("another.child", "child value");

This is how the api needs to be posted

{

   "something":"something value",
   "another": {
   "child": "child value"
   }
}

I get an error stating that the

The another.child field is required.

How do I go about posting this via restAssured? The other APIs do not require posting with nesting work so I'm assuming that's why it's failing.

1

There are 1 answers

1
kaweesha On

Consider another as Json object within the main Json object.

JSONObject requestParams = new JSONObject();
requestParams.put("something", "something value");

JSONObject anotherObject = new JSONObject();
anotherObject.put("child", "child value");

requestParams.put("another", anotherObject);

System.out.println(requestParams.toString());

This will print;

{"another":{"child":"child value"},"something":"something value"}

To pass this Json object to Rest Assured POST method;

    RestAssured.baseURI="base_url";

    RestAssured.given()
            .when()
            .post(requestParams.toString());

Required imports;

import org.json.JSONObject;
import io.restassured.RestAssured;