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
🌐
Baeldung
baeldung.com › home › json › jackson › removing json elements with jackson
Removing JSON Elements With Jackson | Baeldung
January 8, 2024 - In the above example, we iterate through the elements of the JsonNode and remove any element that’s a number and has a value of 30.
🌐
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 object node * @return the object node with empty fields removed */ public static ObjectNode removeEmptyFields(final ObjectNode jsonNode) { ObjectNode ret = new ObjectMapper().createObjectNode(); Iterator<Entry<String, JsonNode>> iter = jsonNode.fields(); while (iter.hasNext()) { Entry<String, JsonNode> entry = iter.next(); String key = entry.getKey(); JsonNode value = entry.getValue(); if (value instanceof ObjectNode) { Map<String, ObjectNode> map = new HashMap<String, ObjectNode>(); map.put(key, removeEmptyFields((ObjectNode)value)); ret.setAll(map); } else if (value instanceof ArrayNode) { ret.set(key, removeEmptyFields((ArrayNode)value)); } else if (value.asText() != null && !value.asText().isEmpty()) { ret.set(key, value); } } return ret; } /** * Removes empty fields from the given JSON array node.
🌐
Fasterxml
fasterxml.github.io › jackson-databind › javadoc › 2.5 › com › fasterxml › jackson › databind › node › ObjectNode.html
ObjectNode (jackson-databind 2.5.0 API)
Method for removing specified field properties out of this ObjectNode. ... Deprecated. Since 2.4 use either set(String,JsonNode) or replace(String,JsonNode),
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java
Jackson: Remove JSON Elements - Java Code Geeks
September 6, 2023 - If the condition is met, we remove the property using ((ObjectNode) jsonNode).remove(property.fieldName()). Finally, we convert the modified JsonNode back to a JSON string using objectMapper.writeValueAsString() and print the result.
🌐
Oracle
docs.oracle.com › cd › E65459_01 › dev.1112 › e65461 › content › conversion_remove_json_node.html
Remove node from JSON document
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. To configure this filter, specify the following fields:
🌐
Fasterxml
fasterxml.github.io › jackson-core › javadoc › 1.9 › org › codehaus › jackson › node › ObjectNode.html
ObjectNode (Jackson JSON Processor)
Type information is needed, even if JsonNode instances are "plain" JSON, since they may be mixed with other types. ... Method that will set specified field, replacing old value, if any. ... value - to set field to; if null, will be converted to a NullNode first (to remove field entry, call remove(java.lang.String) instead)
🌐
Tabnine
tabnine.com › home page › code › java › com.fasterxml.jackson.databind.node.objectnode
com.fasterxml.jackson.databind.node.ObjectNode.remove java code examples | Tabnine
( ( ObjectNode ) properties ).remove( fieldsToRemove ); origin: joelittlejohn/jsonschema2pojo · typeNode.remove("javaType"); origin: stackoverflow.com · import org.codehaus.jackson.node.ObjectNode; // ... for (JsonNode personNode : rootNode) { if (personNode instanceof ObjectNode) { ObjectNode object = (ObjectNode) personNode; object.remove("familyName"); object.remove("middleName"); } } origin: glowroot/glowroot ·
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);
Find elsewhere
🌐
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.
🌐
Javadoc.io
javadoc.io › doc › com.fasterxml.jackson.core › jackson-databind › 2.9.6 › com › fasterxml › jackson › databind › node › ObjectNode.html
ObjectNode - jackson-databind 2.9.6 javadoc
Bookmarks · Latest version of com.fasterxml.jackson.core:jackson-databind · https://javadoc.io/doc/com.fasterxml.jackson.core/jackson-databind · Current version 2.9.6 · https://javadoc.io/doc/com.fasterxml.jackson.core/jackson-databind/2.9.6 · package-list path (used for javadoc generation ...
🌐
Tabnine
tabnine.com › home page › code › java › com.fasterxml.jackson.databind.node.arraynode
com.fasterxml.jackson.databind.node.ArrayNode.remove java code examples | Tabnine
private static void remove(JsonNode node, List<String> path) { if (path.isEmpty()) { throw new RuntimeException("[Remove Operation] path is empty"); } else { JsonNode parentNode = getParentNode(node, path); if (parentNode == null) { throw new RuntimeException("[Remove Operation] noSuchPath in source, path provided : " + path); } else { String fieldToRemove = path.get(path.size() - 1).replaceAll("\"", ""); if (parentNode.isObject()) ((ObjectNode) parentNode).remove(fieldToRemove); else ((ArrayNode) parentNode).remove(Integer.parseInt(fieldToRemove)); } } } origin: org.onosproject/onos-app-routing-api ·
🌐
Oracle
docs.oracle.com › cd › E55956_01 › doc.11123 › user_guide › content › conversion_remove_json_node.html
JSON Remove Node
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. To configure this filter, specify the following fields:
🌐
Jenkov
jenkov.com › tutorials › java-json › jackson-jsonnode.html
Jackson JsonNode
Here is an example that removes a field from a Jackson ObjectNode via its remove() method: ... You can obtain all fields from a JsonNode using the JsonNode fields() method.
🌐
Apps Developer Blog
appsdeveloperblog.com › home › java › java json › modify jsonnode with java jackson
Modify JsonNode with Java Jackson - Apps Developer Blog
August 12, 2022 - class Test { public static void main(String[] args) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); String json = "{\"key1\":\"value1\",\"user\":{\"name\":\"Steve\",\"city\":\"Paris\",\"state\":\"France\"}}"; JsonNode jsonNode = objectMapper.readTree(json); ((ObjectNode) jsonNode).remove("user"); System.out.println(jsonNode.toPrettyString()); } }
🌐
GitHub
github.com › FasterXML › jackson-databind › issues › 4875
Remove `JsonNode.fields()` from 3.0 · Issue #4875 · FasterXML/jackson-databind
December 31, 2024 - Describe your Issue Since JsonNode now has properties() method to replace fields(), let's remove fields() from 3.0.
Author   cowtowncoder