title: Excluding NullNode when serializing a Jackson JSON tree model
body: <p>I have a pojo type that needs to have specific numeric values set to a special string when it's serialized. These values will always be null, possibly pretty deep into a hierarchy. </p>
  
  <p>To accomplish this I first convert the pojo to a JsonNode with nulls intact to preserve property order, then I follow a path through the structure to set some strings and create nodes as necessary. Finally, I have the ObjectMapper serialize the JsonNode to a string. The logic looks something like this:</p>
  
  <pre><code>ObjectMapper nonNullMapper = new ObjectMapper();
  nonNullMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
  
  ObjectMapper includeAllMapper = new ObjectMapper();
  includeAllMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
  
  // NullNodes create stubs to maintain property order
  JsonNode node = includeAllMapper.valueToTree(pojoInstance);
  insertStrings(node);
  
  String json = nonNullMapper.writeValueAsString(node); 
  // Halp, there's still nulls
  </code></pre>
  
  <p>Note that I'm aware there's a <code>@JsonInclude</code> annotation so I don't actually need two mappers, but it turns out that I want to serialize the pojo instances without nulls elsewhere, so I can't use it to my knowledge.</p>
  
  <p>Anyway, how can I avoid having the NullNodes serialized into my string of json? I've found two approaches so far:</p>
  
  <ol>
  <li>Convert to a Map and then serialize to a String, with <code>SerializationFeature.WRITE_NULL_MAP_VALUES</code> disabled. This seems inefficient and hacky.</li>
  <li>Remove NullNode instances manually before serializing the JsonNode. Seems like it shouldn't be necessary given the support for excluding nulls for pojos and maps, and it adds (perhaps?) unneeded complexity.</li>
  </ol>
  
  <p>I tried registering a <code>JsonSerializer</code> for <code>NullNode</code>, but it doesn't appear to get used. I notice that <code>NullNode</code> itself implements <code>JsonSerializable</code>, which simply delegates to the <code>SerializerProvider</code>'s null value serializer. I hesitate to attempt to overwrite this and I feel like the null filtering should be taking place before the values are serialized, but I didn't dig deep enough to understand exactly how it works.</p>
  
  <p>Is there a better way?</p>