Java JsonNode在中间删除一个容器

时间:2018-08-31 22:03:34

标签: java jackson jackson-databind

我有一个以下Json

{
    "Parent": {
        "pk1": "pv1",
        "pk2": "pv2",
        "Child": {
            "*": {
                "ck1": "cv1",
                "ck2": "cv2"
            }
        }
    }
}

现在,我要删除“ *”:{},但保留其内容。预期的输出是这样的。

{
    "Parent": {
        "pk1": "pv1",
        "pk2": "pv2",
        "Child": {
            "ck1": "cv1",
            "ck2": "cv2"
        }
    }
}

我如何使用Java Jackson来实现这一目标?

1 个答案:

答案 0 :(得分:1)

请参阅下面的操作

    ObjectMapper mapper = new ObjectMapper();
    String file = "src/main/resources/yourjson.json";
    JsonNode object = mapper.readTree(new File(file));
    ObjectNode child = (ObjectNode) object.path("Parent").path("Child");
    JsonNode star = child.path("*");
    child.remove("*");
    Iterator<String> startFieldNames = star.fieldNames();
    while (startFieldNames.hasNext()) {
        String startFieldName = startFieldNames.next();
        child.set(startFieldName, star.get(startFieldName));
    }
    System.out.println(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(object));