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.

Answer from gsteff on Stack Overflow
Top answer
1 of 1
3

One thing I would suggest is to split this into a few functions with descriptive names and smaller scopes. First, since we can remove several fields with this function, I think it would be more clearly named removeProperties. (Also, is there a reason that the function name uses "property" and the parameter name uses "field"? It seems to me you could pick one or the other.)

If you split this into single responsibility functions, you get:

public static JsonNode removeProperties(JsonNode node, List<String> removedField){
    JsonNode modifiedNode = node;

    for (String nodeToBeRemoved: removedField){
        modifiedNode = removeProperty(modifiedNode, nodeToBeRemoved);
    }

    return node;
}

A second observation is that it looks like ObjectNode.remove mutates the node. If that's correct, then why bother returning the modified node? Since it's changed in place, you could make this a void function. Or, if the intent is to avoid mutating the provided node, then you'd need to clone it before starting to operate on it. Even if you clone it, remove still changes the node in place, so there's no need for the inner function to return modifiedNode.

I suggest you include JavaDocs specifying whether this function will change the input node or not.


Thirdly, I suggest some renaming here:

String[] array = nodeToBeRemoved.split("/");

To me, this would me more clear as follows, since it makes sense to split a path but I don't know what it means to split a node. We already have a node in context, and its type is JsonNode. If we also call this string a node, then we have two things called "node" which have different types.

String[] pathParts = pathToBeRemoved.split("/");

On the topic of names, I think it would be helpful to extract a variable for the last element:

String keyToRemove = pathParts[pathParts.length - 1];

That way the remove line becomes more clear:

((ObjectNode) nodeToModify).remove(keyToRemove);
🌐
Tabnine
tabnine.com › home page › code › java › com.fasterxml.jackson.databind.node.arraynode
com.fasterxml.jackson.databind.node.ArrayNode.remove java code examples | Tabnine
@Override public void ... } else { JsonNode parentNode = getParentNode(path, Operation.REMOVE); String fieldToRemove = path.get(path.size() - 1).replaceAll("\"", ""); if (parentNode.isObject()) ((ObjectNode) parentNode).remove(fieldToRemove); else if (parentNode.isArray()) ((ArrayNode) parentNode).remove(arrayIndex(fieldToRemove, parentNode.size() - 1, flags.contains(CompatibilityFlags.REMOVE_NONE_EXISTING_ARRAY_ELEMENT))); else ...
🌐
Baeldung
baeldung.com › home › json › jackson › removing json elements with jackson
Removing JSON Elements With Jackson | Baeldung
January 8, 2024 - By using Jackson’s rich set of APIs, we can iterate over the elements of a JsonNode instance and perform conditional checks to identify elements for removal. To remove elements from nested objects or arrays, we follow these steps:
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java
Jackson: Remove JSON Elements - Java Code Geeks
September 6, 2023 - This code will remove the specified key from the JSON data and print the modified JSON string. Here’s the output of the Java code: ... import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; public class RemoveJsonElementsByCondition { public static void main(String[] args) throws Exception { // Create an ObjectMapper ObjectMapper objectMapper = new ObjectMapper(); // Sample JSON string String jsonString = "{\"name\":\"John\",\"age\":30,\"ci
🌐
Fasterxml
fasterxml.github.io › jackson-databind › javadoc › 2.6 › com › fasterxml › jackson › databind › node › ArrayNode.html
ArrayNode (jackson-databind 2.6.0 API)
Method for inserting specified child node as an element of this Array. If index is 0 or less, it will be inserted as the first element; if >= size(), appended at the end, and otherwise inserted before existing element in specified index. No exceptions are thrown for any index. Returns: This node (to allow chaining) public JsonNode remove(int index) Method for removing an entry from this ArrayNode.
🌐
Baeldung
baeldung.com › home › json › jackson › working with tree model nodes in jackson
Working with Tree Model Nodes in Jackson | Baeldung
January 8, 2024 - We’ll use JsonNode for various conversions as well as adding, modifying, and removing nodes.
Find elsewhere
🌐
Baeldung
baeldung.com › home › json › jackson › simplified array operations on jsonnode without typecasting in jackson
Simplified Array Operations on JsonNode Without Typecasting in Jackson | Baeldung
June 27, 2025 - It extends the functionality of JsonNode to include methods for working with arrays, such as adding, removing, and accessing elements by index.
🌐
GitHub
gist.github.com › gkhays › 4fe1e6193e62b1f2cad3bd4b00f16c92
Remove an attribute or element from a JSON array during enumeration · GitHub
July 18, 2018 - JSONArray ja = loadJSONArray(); JSONObject firstJSON = ja.getJSONObject(0); Iterator<?> iter = firstJSON.keys(); for (int i = 0; i < ja.length(); i++) { JSONObject json = ja.getJSONObject(i); while (iter.hasNext()) { String key = iter.next().toString(); if (json.getString(key).equals("null")) { json.remove(key); } } }
🌐
TutorialsPoint
tutorialspoint.com › how-to-remove-a-specific-element-from-a-json-array-in-java
How to remove a specific element from a JSON Array in Java?
You can remove an element from the JSONArray object using the remove() method. This method accepts an integer and removes the element in that particular index. Example
🌐
Technicaldifficulties
technicaldifficulties.io › home › using jackson to remove empty json fields
Using Jackson to Remove Empty JSON Fields | Technical Difficulties
October 23, 2018 - * @param an array node * @return the array node with empty fields removed */ public static ArrayNode removeEmptyFields(ArrayNode array) { ArrayNode ret = new ObjectMapper().createArrayNode(); Iterator<JsonNode> iter = array.elements(); while (iter.hasNext()) { JsonNode value = iter.next(); if (value instanceof ArrayNode) { ret.add(removeEmptyFields((ArrayNode)(value))); } else if (value instanceof ObjectNode) { ret.add(removeEmptyFields((ObjectNode)(value))); } else if (value != null && !value.textValue().isEmpty()){ ret.add(value); } } return ret; }
🌐
Red Hat
access.redhat.com › webassets › avalon › d › red_hat_jboss_enterprise_application_platform › 7.4 › javadocs › com › fasterxml › jackson › databind › node › ArrayNode.html
ArrayNode (Red Hat JBoss Enterprise Application Platform 7.4.0.GA public API)
Method for inserting specified child node as an element of this Array. If index is 0 or less, it will be inserted as the first element; if >= size(), appended at the end, and otherwise inserted before existing element in specified index. No exceptions are thrown for any index. Returns: This node (to allow chaining) public JsonNode remove(int index) Method for removing an entry from this ArrayNode.
🌐
Adobe Developer
developer.adobe.com › experience-manager › reference-materials › 6-5 › javadoc › com › fasterxml › jackson › databind › node › ArrayNode.html
ArrayNode (The Adobe AEM Quickstart and Web Application.)
Method for inserting specified child node as an element of this Array. If index is 0 or less, it will be inserted as the first element; if >= size(), appended at the end, and otherwise inserted before existing element in specified index. No exceptions are thrown for any index. Returns: This node (to allow chaining) public JsonNode remove(int index) Method for removing an entry from this ArrayNode.
🌐
Fasterxml
fasterxml.github.io › jackson-databind › javadoc › 2.9 › com › fasterxml › jackson › databind › node › ArrayNode.html
ArrayNode (jackson-databind 2.9.0 API)
Method for inserting specified child node as an element of this Array. If index is 0 or less, it will be inserted as the first element; if >= size(), appended at the end, and otherwise inserted before existing element in specified index. No exceptions are thrown for any index. Returns: This node (to allow chaining) public JsonNode remove(int index) Method for removing an entry from this ArrayNode.
🌐
Oracle
docs.oracle.com › cd › E65459_01 › dev.1112 › e65461 › content › conversion_remove_json_node.html
Remove node from JSON document
You can use the JSON Remove Node filter to remove a JSON node from a JSON message. You can specify the node to remove using a JSON Path expression. The JSON Path query language enables you to select nodes in a JSON document · For more details on JSON Path, see http://code.google.com/p/jsonpath