java json 去除空,如何用Jackson删除Java中的空json节点?
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":{
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!
解决方案
I want only to show direction how to do that with Json:
JSONObject jsonObj = new JSONObject(_message);
Map map = jsonObj.getMap();
Iterator 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 map = jsonObj.getMap();
Iterator 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() ...
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)