gpt4 book ai didi

java - 无法使用 java jackson java 更新 json 文件

转载 作者:行者123 更新时间:2023-12-02 10:13:53 25 4
gpt4 key购买 nike

json 文件是:

{   
"id": 1,
"name": "TC1",
"steps": [
{
"stepId": 1,
"action": "open",
"object": "chrome",
"input": "https://www.google.com/",

}
]
}

java代码是:

public static void updateTestCaseValue(String tabTCPath) {

ObjectMapper objectMapper = new ObjectMapper();
File jsonFile = new File(tabTCPath);
try {
JsonNode arrNode = objectMapper.readTree(jsonFile).get("steps");
if (arrNode.isArray()) {
for (final JsonNode objNode : arrNode) {
if(objNode.findPath("stepId").asText().equals("1")) {
((ObjectNode) objNode).put("object", "Firefox");
}
objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(tabTCPath), arrNode);
}
}
} catch (IOException e) {
e.printStackTrace();
}

}

输出是:

[ {
"stepId" : 1,
"action" : "openBrowser1",
"object" : "Firefox",
"input" : "https://www.google.com/",
"output" : "",
"description" : "Open browser"
}]

但以下部分未写入文件

"id": 1,
"name": "TC1",

最佳答案

您丢失了对根JsonNode的引用。您需要保留对根节点的引用。另外,在 for-each 循环之后写入结果:

ObjectMapper objectMapper = new ObjectMapper();
JsonNode root = objectMapper.readTree(json);
JsonNode steps = root.get("steps");
if (steps.isArray()) {
for (final JsonNode item : steps) {
if (item.findPath("stepId").asText().equals("1")) {
((ObjectNode) item).put("object", "Firefox");
}
}
String resultJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(root);
System.out.println(resultJson);
}

关于java - 无法使用 java jackson java 更新 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54810416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com