1 つのフィールドを除いて値が null の場合、JsonNode から値を削除する必要があります。JsonNode.Iterator() を使用して JsonNode の反復処理を削除できますが、値のみが得られます。キーであるフィールドsubstitutionItemsを確認する必要があり、フィールドがnullであっても削除しないでください。
public JsonNode stripNulls(JsonNode node) {
log.info("striping nulls");
if(node == null){
return null;
}
Iterator<JsonNode> it = node.iterator();
log.info("tt" + it.hasNext());
while (it.hasNext()) {
JsonNode child = it.next();
if (child.isNull()) {
it.remove();
}
else{
if(child.get("promotion") != null){
continue;
}else{
stripNulls(child);
}
}
}
}
JsonNode.fields() を使用してキーと値のペアを取得しようとしており、フィールドがsubstitutionItemsであるかどうかを確認して、削除しないか、削除してください。
public JsonNode stripNulls(JsonNode node) {
log.info("striping nulls");
if(node == null){
return null;
}
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
log.info("dd " + fields.hasNext());
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
log.info("contains" + field.getKey() + " --- " + field.getValue());
if(field.getValue().isNull() && !field.getKey().equals("substitutionItems")) {
log.info("to remove " + field.getKey() + " --- " + field.getValue());
fields.remove();
}
else{
if(field.getValue().get("promotion") != null){
continue;
}else{
stripNulls(field.getValue());
}
}
}
}
しかしそうすると、 fields.hasNext()は false を返します。
どうすれば望ましい結果を得ることができますか?