[英]How to use variable in .json file and change it in java
I have a.json file and i read it to use Files.readAllBytes(Paths.get("classpath"))
.我有一个 .json 文件,我读取它以使用
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.它可以工作,但我需要在.json 文件中使用变量,我只想用其他方法更改变量。
Here is my.json file:这是我的.json 文件:
{
"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.当我读取.json 文件时,我想在此方法中更改用户名。 How can do that?
怎么能这样做?
Thank you for your advice感谢您的意见
Your user name is stored in invitees Array
so you need to replace that.您的用户名存储在受邀者
Array
中,因此您需要替换它。 For that, we can use JSONObject
like below,为此,我们可以像下面这样使用
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\"}]"));
In your code,在您的代码中,
response = header.body(jsonObject.toString())
.when()
.post("/shares")
.then()
.assertThat()
.extract()
.response();
Output: 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.