我有一些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