gpt4 book ai didi

Java JsonNode 删除中间一个容器

转载 作者:行者123 更新时间:2023-12-02 10:51:48 30 4
gpt4 key购买 nike

我有以下 Json

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

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

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

如何使用 Java Jackson 来实现此目的?

最佳答案

请参阅下面的操作

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

关于Java JsonNode 删除中间一个容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52123061/

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