How to use variable in .json file and change it in java

Viewed 41

I have a .json file and i read it to use Files.readAllBytes(Paths.get("classpath")). It works but i need to use variable in .json file and i just want to change variable in other method.

Here is my .json file:

    {
  "type": "FILE",
  "invitationMessage": "",
  "duration": "NO_EXPIRE",
  "items": [
    {
      "uuid": "shdy28-9b03-4c21-9c80-f96f31f9cee9",
      "projectId": "65ht8f99694454a658yef17a95e8f"
    }
  ],
  "invitees": [
    {
      "username": "variable@gmail.com",
      "role": "VIEWER"
    }
  ]
}

This is the method I used the file:

@When("^I send share privately api$")
public void sharePrivately() throws IOException {

    String body = new String(Files.readAllBytes(Paths.get("src/test/resources/config/environments/sharePrivately.json")));
    

    RequestSpecification header = rh.share(payload.userAuth());

    response = header.body(body)
            .when()
            .post("/shares")
            .then()
            .assertThat()
            .extract()
            .response();
    System.out.println(response.getStatusCode());
    }

When i read .json file i want to change username in this method. How can do that ?

Thank you for your advice

1 Answers

Your user name is stored in invitees Array so you need to replace that. For that, we can use JSONObject like below,

    String body = new String(Files
            .readAllBytes(Paths.get("src/test/resources/config/environments/sharePrivately.json")));
    JSONObject jsonObject = new JSONObject(body);
    jsonObject.put("invitees", new JSONArray("[{\"username\": \"Nandan@gmail.com\",\"role\": \"VIEWER\"}]"));

In your code,

response = header.body(jsonObject.toString())
            .when()
            .post("/shares")
            .then()
            .assertThat()
            .extract()
            .response();

Output:

{
    "duration": "NO_EXPIRE",
    "invitees": [
        {
            "role": "VIEWER",
            "username": "Nandan@gmail.com"
        }
    ],
    "invitationMessage": "",
    "type": "FILE",
    "items": [
        {
            "uuid": "shdy28-9b03-4c21-9c80-f96f31f9cee9",
            "projectId": "65ht8f99694454a658yef17a95e8f"
        }
    ]
}

You need to use below import,

    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20160212</version>
    </dependency>
Related