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",
答案 0 :(得分:1)
您丢失了对根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);
}