Search code examples
javajsonjackson

Removing JSON elements with Jackson


I've a particular JSON node that corresponds to org.codehaus.jackson.JsonNode, and not 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"
    }
]

I want to remove "familyName" and "middleName" from all the JSON nodes of the above array. Is there any way to achieve this?


Solution

  • I haven't tested this, but I think something like this would do what you want:

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

    You could also do this more efficiently using Jackon's raw parsing API, but the code would be a lot messier.