Issue
The ask is to remove a JSON element from a JSON file: In this case its ID element. I am able to get the desired result. But the code looks very verbose can it be written in a better way without hindering the performance.
The path for the same is provided from the root node: /glossary/GlossDiv/GlossList/GlossEntry/ID
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
The code to remove the element is: As one can observe it has two for loops and we are traversing to the parent of the element which needs to be removed and then removing the element. Is there a better way of writing the code?
public static JsonNode removeProperty(JsonNode node, List<String> removedField){
JsonNode modifiedNode = node;
for (String nodeToBeRemoved: removedField){
String[] array = nodeToBeRemoved.split("/");
for (int i =1;i<array.length-1;i++){
String name=array[i];
modifiedNode = modifiedNode.get(name);
}
((ObjectNode)modifiedNode).remove(array[array.length-1]);
}
return node;
}
Solution
You could use JsonPointer
for it, e.g.
String path = "/glossary/GlossDiv/GlossList/GlossEntry/ID";
String nodeToRemove = path.substring(path.lastIndexOf('/')+1);
JsonPointer jp = JsonPointer.compile(path.substring(0, path.lastIndexOf('/')));
ObjectNode parent = (ObjectNode)node.at(jp);
parent.remove(nodeToRemove);
The JsonPointer
can also be cached.
Answered By - Kayaman
Answer Checked By - Candace Johnson (JavaFixing Volunteer)