Reputation: 51
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
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
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
Reputation: 322
Check this
How to not send an empty collection in jackson
For empty node in Json you can use
Removing JSON elements with jackson
These can solve your problem.
Upvotes: 1