4

I have a JsonObject created using Google Gson.

JsonObject jsonObj = gson.fromJson(response1_json, JsonElement.class).getAsJsonObject();

Also i made some modification to existing jsonobj as below :

JsonObject newObject = new JsonObject();
            newObject.addProperty("age", "50");
            newObject.addProperty("name", "X");
jsonObj.get("data").getAsJsonArray().add(newObject);

Now, using rest assured, i need to send the post request with this jsonobject. I tried the following but it doesn't work and throws exception:

Response postResponse = 
                    given()
            .cookie(apiTestSessionID)
            .header("Content-Type", "application/json")
            .body(jsonObj.getAsString())
            .when()
            .post("/post/Config");

Please guide me on this.

ButterSkotch
  • 75
  • 1
  • 1
  • 6

1 Answers1

6

Try below code to send Json to a Post request using Rest-assured

//Get jsonObject from response
JsonObject jsonObj = gson.fromJson(response1_json, JsonElement.class).getAsJsonObject();


//Create new jsonObject and add some properties
JsonObject newObject = new JsonObject();
    newObject.addProperty("age", "50");
    newObject.addProperty("name", "X");

//Get jsonarray from jsonObject
JsonArray jArr = jsonObj.get("data").getAsJsonArray();

//Add new Object to array
jArr.add(newObject);

//Update new array back to jsonObject
jsonObj.add("data", jArr);

Response postResponse = 
                given()
        .cookie(apiTestSessionID)
        .contentType("application/json")
        .body(jsonObj.toString())
        .when()
        .post("/post/Config");
Purushotham
  • 3,770
  • 29
  • 41