簡體   English   中英

無法使用Java Jackson Java更新json文件

[英]Not able to java update json file using java jackson

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM