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 - 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.
🌐
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; }
🌐
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.
🌐
Tabnine
tabnine.com › home page › code › java › com.fasterxml.jackson.databind.node.objectnode
com.fasterxml.jackson.databind.node.ObjectNode.remove java code examples | Tabnine
@Override public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { ObjectMapper mapper = (ObjectMapper) p.getCodec(); ObjectNode root = mapper.readTree(p); Iterator<Map.Entry<String, JsonNode>> iterator = root.fields(); while (iterator.hasNext()) { Map.Entry<String, JsonNode> entry = iterator.next(); if (entry.getKey().equals(TYPE_KEY)) { Class<? extends T> configClass = concreteFactory.apply(entry.getValue().asText()); root.remove(TYPE_KEY); return mapper.convertValue(root, configClass); } } throw new ConfigurationException("Failed to deserialize polymorphic " + _valueClass.getSimpleName() + " configuration"); } } origin: Graylog2/graylog2-server ·
🌐
Baeldung
baeldung.com › home › json › jackson › working with tree model nodes in jackson
Working with Tree Model Nodes in Jackson | Baeldung
January 8, 2024 - ObjectNode locatedNode = locatedNode.remove(fieldNames); In the extreme case when we want to delete all subnodes of a given node, the removeAll API comes in handy. The following test will focus on the first method mentioned above, which is the ...
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);
🌐
Oracle
docs.oracle.com › cd › E65459_01 › dev.1112 › e65461 › content › conversion_remove_json_node.html
Remove node from JSON document
To configure this filter, specify the following fields: ... Enter a suitable name that reflects the role of the filter. ... Enter a JSON Path expression to specify the node to remove (for example, $.store.bicycle).
🌐
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),
Find elsewhere
🌐
Oracle
docs.oracle.com › cd › E55956_01 › doc.11123 › user_guide › content › conversion_remove_json_node.html
JSON Remove Node
To configure this filter, specify the following fields: ... Enter a suitable name that reflects the role of the filter. ... Enter a JSON Path expression to specify the node to remove (for example, $.store.bicycle).
🌐
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 ...
🌐
Medium
medium.com › knowledge-pills › how-do-i-remove-a-property-from-a-json-object-fd7ec14d37bd
How to remove a property from a JSON object? | by Fuji Nguyen | Knowledge Pills | Medium
January 8, 2024 - How to remove a property from a JSON object? To remove a property from a JSON object in JavaScript, you can use the delete operator. Here is an example of how to use the delete operator to remove the …
🌐
Axway
support.axway.com › kb › 178417 › language › en
JSON Remove Node
Select 'Add as a new item' option and specify the deleted node's name as the name for that value. Enter the following selector in the "Content" field: ${deleted.json.node.list["$_0"]}
🌐
Stack Overflow
stackoverflow.com › questions › 53833735
java - Remove jsonnode which contains a specific word - Stack Overflow
December 17, 2018 - I tried remove and removeAll method , with that i am able to remove specific field but need to pass full exact name of field.