我有一些JSON,像这样:如何删除空节点JsonNode
String str = "{\"menu\":[{\"form1\":\"nameForm1\"}, {\"form2\":\"nameForm2\"}]}";
ObjectMapper objectMapper = new ObjectMapper();
JsonNode testNode = objectMapper.readTree(str);
一些动作后,我修改了JSON。例如
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();
}
}
}
}
而我的JSON开始看起来像:
{"menu":[{},{"form2":"nameForm2"}]}
我怎样才能获得JSON没有空数组元素,即
{"menu":[{"form2":"nameForm2"}]}
有吨JSON库在那里的代码。你使用哪一个? – Henry
你需要从条目中删除arrayNode,目前你只是删除arrayNode的属性 –
我使用com.fasterxml.jackson – alex