/**
* This method removes given key from JsonNode.
*
* @param jsonNode
* @return
*/
public static void removeGivenKeyFromJsonNode(@NonNull final JsonNode jsonNode,
@NonNull final String key) {
if (jsonNode.isObject()) {
final Iterator<String> iterator = jsonNode.fieldNames();
while (iterator.hasNext()) {
final String currentNodeName = iterator.next();
final JsonNode currentNode = jsonNode.get(currentNodeName);
if (StringUtils.equals(currentNodeName, key)) {
iterator.remove(); //To avoid concurrentModificationException
((ObjectNode) jsonNode).remove(currentNodeName);
} else {
// If field is Array then again search in all the array nodes.
if (currentNode.isArray()) {
removeGivenKeyFromJsonNode(currentNode, key);
}
removeGivenKeyFromJsonNode(currentNode, key);
}
}
} else if (jsonNode.isArray()) {
jsonNode.forEach(arrayElement -> {
removeGivenKeyFromJsonNode(arrayElement, key);
});
}
}
No comments:
Post a Comment
Add Your comments here...