I want the jackson to ignore the null values when putting them into the instance of ObjectNode. (I know how to prevent nulls when serializing a pojo) Here i am manually putting the the key/values in ObjectNode instance and i want the jackson to ignore the key/value to ignore when value is null.
for example
objectNode.put("Name", null);
should be ignored and does not get inserted to objectNode.
You can use SerializationFeature.WRITE_NULL_MAP_VALUES feature but before you have to convert your ObjectNode object to Map.
See below example:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
String nullValue = null;
ObjectNode subNode = new ObjectNode(mapper.getNodeFactory());
subNode.put("test", 1);
subNode.put("nullValue", nullValue);
ObjectNode node = new ObjectNode(mapper.getNodeFactory());
node.put("notNull", "Not null.");
node.put("nullValue", nullValue);
node.set("subNode", subNode);
MapType mapType = mapper.getTypeFactory().constructMapType(Map.class, String.class, Object.class);
Object mapValue = mapper.convertValue(node, mapType);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(mapValue));
Above program prints:
{
"notNull" : "Not null.",
"subNode" : {
"test" : 1
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With