user2842643
user2842643

Reputation: 51

How do I remove empty json nodes in Java with Jackson?

I'm a beginning java programmer, so I'm sorry if my question is kind of dumb.

I have a JSON object that looks like this:

{
"element1" : {
    "generated_name_1": {
        "a" : {"isReady":false}
    },
    "generated_name_2":{},
    "generated_name_3":{},
    "generated_name_4":{}
},
"element2" : {
    "generated_name_5" : {
        "a" : {"isReady":false},
        "g" : {"isReady":false}
    }
},
"element3" : { 
    "a" : { "isReady":false},
    "n":{}
}
}

I would like to go through and delete every element that has an empty value associated with it, like "generated_name_2" and "n". I have no idea what the names of those elements would be, and I have no idea how far nested into the JSON tree it is.

I get that I have to write a recursive program, and this is what I came up with:

public static void cleanJsonNodes(ObjectNode myJsonNode){
    for (JsonNode currentNode : myJsonNode){
        if (currentNode.size() == 0){
            myJsonNode.remove(currentNode);
        } else {
            cleanJsonNodes((ObjectNode)currentNode);
        }
    }
}

Of course, this doesn't work, but I'm not really sure where to go from here and I've scoured the internet to no avail.

Please someone help me!

Upvotes: 5

Views: 14726

Answers (3)

Neil
Neil

Reputation: 4049

I haven't tested it, but you probably want something like this:

public static void stripEmpty(JsonNode node) {
    Iterator<JsonNode> it = node.iterator();
    while (it.hasNext()) {
        JsonNode child = it.next();
        if (child.isObject() && child.isEmpty(null))
            it.remove();
        else
            stripEmpty(child);
    }
}

Upvotes: 4

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

I want only to show direction how to do that with Json:

JSONObject jsonObj = new JSONObject(_message);

    Map<String, JSONObject> map = jsonObj.getMap();

    Iterator<String> it = map.keySet().iterator();

    while(it.hasNext()){
          String key =   it.next();

          JSONObject o = map.get(key);

          if(o.length() == 0){
              it.remove();
          }
    }

When JSONObject loads {} its length is 0, therefore you can drop it.

As A side note, you can use this method in recursion like:

JSONObject jsonObj = new JSONObject(_message);

invoke(jsonObj);

...

private static void invoke(JSONObject jsonObj) {
    Map<String, JSONObject> map = jsonObj.getMap();

    Iterator<String> it = map.keySet().iterator();

    while(it.hasNext()){
        String key =   it.next();

        JSONObject o = map.get(key);

        if(o.length() == 0){
            it.remove();
        }
        else{
            invoke(o);
        }
    }
}

I didn't add any validation but for sure , you need to verify instance of jsonObj.getMap() ...

Upvotes: 2

Related Questions