如何在.json文件中使用变量并在java中进行更改



我有一个.json文件,我读取它以使用Files.readAllBytes(Paths.get("classpath"))。它有效,但我需要在.json文件中使用变量,我只想在其他方法中更改变量。

这是我的.json文件:

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

这是我使用的方法文件:

@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());
}

当我读取.json文件时,我想用这种方法更改用户名。怎么能做到呢?

谢谢你的建议

您的用户名存储在受邀者Array中,因此您需要替换它。为此,我们可以像下面这样使用JSONObject

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"}]"));

在您的代码中,

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

输出:

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

您需要使用以下导入,

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

最新更新