Java JsonNode 删除中间的一个容器

我有以下 Json


{

    "Parent": {

        "pk1": "pv1",

        "pk2": "pv2",

        "Child": {

            "*": {

                "ck1": "cv1",

                "ck2": "cv2"

            }

        }

    }

}

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


{

    "Parent": {

        "pk1": "pv1",

        "pk2": "pv2",

        "Child": {

            "ck1": "cv1",

            "ck2": "cv2"

        }

    }

}

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


湖上湖
浏览 316回答 1
1回答

不负相思意

看下面的操作&nbsp; &nbsp; ObjectMapper mapper = new ObjectMapper();&nbsp; &nbsp; String file = "src/main/resources/yourjson.json";&nbsp; &nbsp; JsonNode object = mapper.readTree(new File(file));&nbsp; &nbsp; ObjectNode child = (ObjectNode) object.path("Parent").path("Child");&nbsp; &nbsp; JsonNode star = child.path("*");&nbsp; &nbsp; child.remove("*");&nbsp; &nbsp; Iterator<String> startFieldNames = star.fieldNames();&nbsp; &nbsp; while (startFieldNames.hasNext()) {&nbsp; &nbsp; &nbsp; &nbsp; String startFieldName = startFieldNames.next();&nbsp; &nbsp; &nbsp; &nbsp; child.set(startFieldName, star.get(startFieldName));&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(object));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java