Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent NULL values insertion to ObjectNode in jackson

Tags:

json

jackson

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.

like image 920
Vivek Avatar asked Feb 05 '26 11:02

Vivek


1 Answers

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
  }
}
like image 93
Michał Ziober Avatar answered Feb 07 '26 02:02

Michał Ziober