Reputation: 2028
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?
Upvotes: 5
Views: 4216
Reputation: 7844
nafas' answer seems to provide you what you need for this problem. Just as an alternative approach: removing the unwanted objects may be tied to a single use case, so it may be ideal to decouple the removal from the deserialization. You could do so by deserializing your JSON as it is, and then filtering out the unwanted objects when you need to.
An object like this will allow you to translate your JSON to Java and perform operations on the data in a more formalized way compared to using JsonNode
. Not sure how Jackson behaves with spaces in property names, this is just to match the example JSON given.
public class CustomPojo {
private final Integer keyToKeep;
private final String keyToRemove;
@JsonCreator
public CustomPojo(@JsonProperty("Lorem Ipsum ") Integer keyToKeep,
@JsonProperty("keyToRemove") String keyToRemove) {
this.keyToKeep = keyToKeep;
this.keyToRemove = keyToRemove;
}
@JsonProperty("Lorem Ipsum ")
public Integer getKeyToKeep() {
return keyToKeep;
}
@JsonProperty("keyToRemove")
public String getKeyToRemove() {
return keyToRemove;
}
}
Adding a method to remove the objects will decouple the removal from deserialization. Assuming you will deserialize your JSON into an array in your resource.
public class CustomPojoService {
public static List<CustomPojo> removeUnwantedKeys(List<CustomPojo> customPojoArray) {
return customPojoArray.stream().filter(
customPojo -> customPojo.getKeyToRemove() == null
).collect(Collectors.toList());
}
}
Upvotes: 2
Reputation: 5423
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();
}
}
};
Upvotes: 5