Abhi Narwal
Abhi Narwal

Reputation: 87

How to store RESTAssured Output to file in JSON Format

I am storing a response from POST call which I make using REST Assured. I want to store response in a file in JSON format, as I will be needing the body next to make a PUT call. Currently I am able to store response to a file, but it stores in String format. How can i convert it to JSON format?

 @Test
public void postIt() throws Exception {
    if(Ver>=currentVer) {
        InputStream resource = getClass().getClassLoader().getResourceAsStream("inputJSONBody.json");
        String json = IOUtils.toString(resource);
        System.out.println(json);
        Response response = given().contentType("application/json").accept("application/json").body(json).when().post("/APIURI");
        String responseBody = response.getBody().asString();
        response.then().statusCode(201);

        try {

            FileWriter file = new FileWriter("./output.json");
            file.write(responseBody);
            file.flush();
            file.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

Upvotes: 1

Views: 5821

Answers (2)

Afsal
Afsal

Reputation: 494

You can do it with this sample code:

FileWriter file = new FileWriter("./output.json");
file.write(responseBody.prettyPrint());
file.flush();
file.close();

Upvotes: 0

Abhi Narwal
Abhi Narwal

Reputation: 87

I was able to do it using prettyPrint() feature offered by REST Assured

Upvotes: 2

Related Questions