Java更新JSON键值未生效问题求助及解决方案分享
问题分析与解决方案:JSON日期替换失效问题
问题背景
我编写了一段Java代码,试图将JSON文件中的"runTimeDate"值,以及包含"keyDate"的键名替换为当前日期加180天的字符串(格式yyyy-MM-dd),但运行后发现日期并未更新。
原始代码实现
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 + "\""); }
示例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" } } } } }
测试调用代码
@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(); }
问题分析
原始代码存在两个核心问题:
- 未读取JSON文件内容:
jsonFile变量仅存储了文件路径字符串,而非文件的实际内容。调用replaceAll只是对路径字符串做替换,完全没有触及JSON文件里的内容,这是日期未更新的根本原因。 - 键名匹配不完整:JSON中的键是
"keyDate|AUS|1234|SYD|MEL"这类带后缀的格式,而代码里仅替换"keyDate",无法匹配完整的键名,导致键名替换失效。
可行解决方案(基于ObjectMapper)
通过先读取JSON文件内容,再做全局字符串替换,最后解析为JsonNode供接口测试使用,解决了上述问题。
核心处理方法
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; }
辅助JSON读取方法
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(); } }
注:项目存在第三方库使用限制,该方案基于Jackson的ObjectMapper实现,符合常规Java项目依赖范围。
内容的提问来源于stack exchange,提问作者gg_man
相关产品推荐
相关产品推荐

