使用 jackson 删除 JSON 元素

2022-09-01 01:35:56

我有一个特定的JSON Node,对应于import org.codehaus.jackson.JsonNode,而不是import org.codehaus.jackson.map.JsonNode。

[
    {
        "givenName": "Jim",
        "formattedName": "jimJackson",
        "familyName": null,
        "middleName": "none",
        "honorificPrefix": "mr",
        "honorificSuffix": "none"
    },
    {
        "givenName": "john",
        "formattedName": "johnLasher",
        "familyName": null,
        "middleName": "none",
        "honorificPrefix": "mr",
        "honorificSuffix": "none"
    },
    {
        "givenName": "carlos",
        "formattedName": "carlosAddner",
        "familyName": null,
        "middleName": "none",
        "honorifiPrefix": "mr",
        "honorificSuffix": "none"
    },
    {
        "givenName": "lisa",
        "formattedName": "lisaRay",
        "familyName": null,
        "middleName": "none",
        "honorificPrefix": "mrs",
        "honorificSuffix": "none"
    },
    {
        "givenName": "bradshaw",
        "formattedName": "bradshawLion",
        "familyName": null,
        "middleName": "none",
        "honorificPrefix": "mr",
        "honorificSuffix": "none"
    },
    {
        "givenName": "phill",
        "formattedName": "phillKane",
        "familyName": null,
        "middleName": "none",
        "honorificPrefix": "mr",
        "honorificSuffix": "none"
    },
    {
        "givenName": "Gabriel",
        "formattedName": "gabrielMoosa",
        "familyName": null,
        "middleName": "none",
        "honorificPrefix": "mr",
        "honorificSuffix": "none"
    }
]

我想从上述数组的所有JSON节点中删除“familyName”和“middleName”。有没有办法做到这一点?


答案 1

我还没有测试过这个,但我认为这样的东西可以做你想要的:

import org.codehaus.jackson.node.ObjectNode;
// ...
for (JsonNode personNode : rootNode) {
    if (personNode instanceof ObjectNode) {
        ObjectNode object = (ObjectNode) personNode;
        object.remove("familyName");
        object.remove("middleName");
    }
}

你也可以使用Jackon的原始解析API更有效地做到这一点,但代码会更混乱。


答案 2

Jackson的ObjectMapper给出了只有几步的解决方案。

将 json 数据保存在一个文件“data.json”中。将代码后面的代码复制到不带 import 语句的函数中,然后调用该函数。生成的 JSON 将写入新文件“data1.json”。

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(new File("data.json"));
        for (JsonNode node : jsonNode) {
            ((ObjectNode)node).remove("familyName");
            ((ObjectNode)node).remove("middleName");
        }
        objectMapper.writeValue(new File("data1.json"), jsonNode);