I have the following code to update the key "runTimeDate" within my json file.
`final LocalDate plus180Days = LocalDate.now().plusDays(180);
DateTimeFormatter dateTimeFormatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd");
String substituteDate = plus180Days.format(dateTimeFormatter);
String jsonFile = "src/examples/sample.json";
public String Body_ValueDate()
{
return jsonFile.replaceAll("\"runTimeDate\"", "\"" + substituteDate +
"\"");
}
public String Body_KeyDate()
{
return Body_ValueDate().replaceAll("\"keyDate\"", "\"" +
substituteDate + "\"");
}`
I used the code above from here: https://stackoverflow.com/questions/7463414/what-s-the-best-way-to-load-a-jsonobject-from-a-json-text-file#:~:text=23-,With%20java%208,-you%20can%20try
Thing is, the date is not getting updated. plus180Days is basically a function adding 180 days from current date. Can anyone share what I am missing here?
final LocalDate plus180Days = LocalDate.now().plusDays(180);
Sample Json
{
"city": {
"details": {
"a1": "AUS",
"a2": "AUS",
"country": "AUS"
}
},
"detail": {
"getCountryDetail": {
"b1": "SYD",
"b2": "MEL",
"country": {
"keyDate|AUS|1234|SYD|MEL": {
"date1": "runTimeDate",
"time1": "15:38",
"date2": "runTimeDate",
"time2": "19:13"
},
"keyDate|AUS|1234|ADL|MEL": {
"date1": "runTimeDate",
"time1": "15:38",
"date2": "runTimeDate",
"time2": "19:13"
}
}
}
}
}
I am using the updated json method "Body_KeyDate" as body parameter for my rest assured method as per here:
@Test
public void UA_Avail_Cascading_Request()
throws IOException
{
Response response = RestAssured.given()
.header(readConfigFile())
.contentType("application/json")
.body(Body_KeyDate())
.when()
.post(readBaseUrl() + "samplePage")
.then().statusCode(200)
.log().all()
.extract().response();
}
Following solution worked: with ObjectMapper
public JsonNode RequestBody_DynamicDate() throws Exception
{
String requestBodyJson = loadJson("Sample.json");
String removeKeyDate = requestBodyJson.replace("keyDate", NEW_DATE);
String removeValueDate = removeKeyDate.replace("runTimeDate", NEW_DATE);
JsonNode processedNewDates = OBJECT_MAPPER.readTree(removeValueDate);
System.out.println("New JSON Body: "
+ OBJECT_MAPPER
.writerWithDefaultPrettyPrinter()
.writeValueAsString(processedNewDates));
return processedNewDates;
}
Here is the code for loadJson
: BASEPATH
is the folder location
String loadJson(String filePath)
{
try
{
return new String(Files.readAllBytes(Paths.get(BASEPATH + filePath)));
}
catch (Exception e)
{
Assertions.fail("unable to load test data, check file path, and format");
throw new RuntimeException();
}
Hope this helps someone. Also turns there was some restrictions and limitations on which library and packages can be used.