2

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.

Vivek
  • 11,938
  • 19
  • 92
  • 127
  • Have you seen this question: http://stackoverflow.com/questions/11757487/how-to-tell-jackson-to-ignore-a-field-during-serialization-if-its-value-is-null? – Michał Ziober Aug 13 '14 at 14:08
  • @MichałZiober i am not serializing a pojo to json, i am manually constructing a json, so i can not use annotations. – Vivek Aug 14 '14 at 05:00
  • 1
    Could you give me a little example how you are constructing this `JSON`? Good example is better that 1000 words - I think it will help us to understand your problem better. – Michał Ziober Aug 14 '14 at 07:43

3 Answers3

3

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
  }
}
Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
  • 1
    I am using jackson v1.9. mapper.configure(org.codehaus.jackson.map.SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, false); and it worked :) – Vivek Aug 14 '14 at 13:02
  • Thanks for sharing your solution. In my example I am using v2.4.1 and `com.fasterxml` implementation. – Michał Ziober Aug 14 '14 at 13:10
0

You can use

ObjectNode.putNull(FieldName)
vimuth
  • 5,064
  • 33
  • 79
  • 116
0

one can use now

objectNode.put("PropName", NullNode.getInstance());
davey
  • 1,666
  • 17
  • 24