简体   繁体   English

如何在JsonNode中删除空节点

[英]How to remove empty node in JsonNode

i have some json, like this: 我有一些json,像这样:

String str = "{\"menu\":[{\"form1\":\"nameForm1\"}, {\"form2\":\"nameForm2\"}]}";
ObjectMapper objectMapper = new ObjectMapper();
JsonNode testNode = objectMapper.readTree(str);

After some actions, I modified my json. 经过一些操作后,我修改了json。 for example 例如

Iterator<Map.Entry<String, JsonNode>> fieldIterator = testNode.fields();
while (fieldIterator.hasNext()) {
    Map.Entry<String, JsonNode> entry = fieldIterator.next();
    if (entry.getValue().isArray()){
        for (JsonNode arrayNode : entry.getValue()){
            if (arrayNode.path("form2").isMissingNode()) {
                ((ObjectNode) arrayNode).removeAll();
           }
        }
    }
}

And my json began to look like: 我的json开始看起来像:

{"menu":[{},{"form2":"nameForm2"}]}

How can I get json without empty array elements, ie 我如何在没有空数组元素的情况下获取json,即

{"menu":[{"form2":"nameForm2"}]}

As I pointed in comment you need to remove arrayNode variable(which must be named as arrayElementNode ) from arrayNode(which is entry.getValue()), currently you are just removing arrayNode's(arrayElementNode's) properties 正如我在评论中指出的那样,您需要从arrayNode(即entry.getValue())中删除arrayNode变量(必须命名为arrayElementNode),当前您只是在删除arrayNode的(arrayElementNode的)属性

Here is the code with this logic 这是具有这种逻辑的代码

Iterator<Map.Entry<String, JsonNode>> fieldIterator = testNode.
while (fieldIterator.hasNext()) 
{
   Map.Entry<String, JsonNode> entry = fieldIterator.next();
   if (entry.getValue().isArray())
   {
      ArrayNode arrayNode = (ArrayNode) entry.getValue();
      for(int i = arrayNode.size()-1; i >= 0 ; i--)
      {
         if(arrayNode.get(i).path("form2").isMissingNode())
            arrayNode.remove(i);

     }
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM