I'm trying to remove an element from a JSON file:
[
{
"Lorem Ipsum ":4,
},
{
"Lorem Ipsum ":5,
},
{
"keyToRemove": value,
}
]
With the following code, I can remove the key and the value:
for (JsonNode personNode : rootNode) {
if (personNode instanceof ObjectNode) {
if (personNode.has("keyToRemove")) {
ObjectNode object = (ObjectNode) personNode;
object.remove("keyToRemove");
}
}
}
But I still have an empty bracket:
[
{
"Lorem Ipsum ":4,
},
{
"Lorem Ipsum ":5,
},
{
}
]
How can I remove it?
you are not removing the whole object, but instead you are removing an element of it.
object.remove("keyToRemove");
will remove an element keyToRemove
from your object
. in this case object
is basically json object
not the json array
.
To remove the whole object you shouldn't be using a for loop
.
you can try using an Iterator
instead:
Iterator<JsonNode> itr = rootNode.iterator();
while(itr.hasNext()){
JsonNode personNode = itr.next();
if(personNode instanceof ObjectNode){
if (personNode.has("keyToRemove")) {
// ObjectNode object = (ObjectNode) personNode;
// object.remove("keyToRemove");
itr.remove();
}
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With