Remove empty item from JSON file using Jackson

I am trying to remove an item from a JSON file:

[ { "Lorem Ipsum ":4, }, { "Lorem Ipsum ":5, }, { "keyToRemove": value, } ] 

With the following code, I can remove the key and 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 to remove it?

+5
source share
2 answers

you do not delete the entire object, but instead you delete its element.

 object.remove("keyToRemove"); 

will remove the keyToRemove element from your object . in this case, the object is basically a json object not a json array .

To delete an entire object, you should not use for loop . you can try instead of Iterator :

  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(); } } }; 
+5
source

Strive for reuse

Answer

nafas seems to give you what you need for this problem. Similar to an alternative approach: removing unwanted objects can be tied to a single use case, therefore it can be ideal to separate the removal from deserialization. You can do this by deserializing your JSON as it is, and then filter out unwanted objects when you need to.

Create an object that represents your JSON

Such an object will allow you to translate JSON into Java and perform operations on data in a more formalized way compared to using JsonNode . You donโ€™t know how Jackson behaves with spaces in property names, it just follows the JSON example.

 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; } } 

Add a method to remove unwanted objects

Adding a method to delete objects will cancel the deletion from deserialization. Assuming you will deserialize your JSON into an array of your resource.

 public class CustomPojoService { public static List<CustomPojo> removeUnwantedKeys(List<CustomPojo> customPojoArray) { return customPojoArray.stream().filter( customPojo -> customPojo.getKeyToRemove() == null ).collect(Collectors.toList()); } } 
+2
source

All Articles