0

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": "[email protected]",
      "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
  • 1
    Parse the json - eg. into a generic structure like JsonObject etc. - , change the data as needed and reserialize it to json. Commented Sep 13, 2022 at 10:22

1 Answer 1

1

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\": \"[email protected]\",\"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": "[email protected]"
        }
    ],
    "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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.