Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove an empty element from JSON file with Jackson

Tags:

java

json

jackson

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?

like image 355
Grégoire Borel Avatar asked Jun 18 '15 13:06

Grégoire Borel


1 Answers

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();
           }
        }
    };
like image 51
nafas Avatar answered Nov 02 '22 03:11

nafas