Jackson 2.6.3 Deserialization avoid literal null added to collection
I got an inspiration from the following post
Jackson: Ignore whitespace in empty @XmlWrapperElement collection
Here is the solution specific to the question above
public class NullCollectionHandler extends SimpleModule { private static class CustomizedCollectionDeserialiser extends CollectionDeserializer { public CustomizedCollectionDeserialiser(CollectionDeserializer src) { super(src); } private static final long serialVersionUID = 1L; @Override public Collection<Object> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Collection<Object> oldCol = super.deserialize(jp, ctxt); Collection<Object> newCol = new ArrayList<Object>(); if(CollectionUtils.isNotEmpty(oldCol)){ for(Object obj : oldCol){ if(obj != null) newCol.add(obj); } } return newCol; } @Override public CollectionDeserializer createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException { return new CustomizedCollectionDeserialiser(super.createContextual(ctxt, property)); } } private static final long serialVersionUID = 1L; @Override public void setupModule(SetupContext context) { super.setupModule(context); context.addBeanDeserializerModifier(new BeanDeserializerModifier() { @Override public JsonDeserializer<?> modifyCollectionDeserializer( DeserializationConfig config, CollectionType type, BeanDescription beanDesc, JsonDeserializer<?> deserializer) { if (deserializer instanceof CollectionDeserializer) { return new CustomizedCollectionDeserialiser( (CollectionDeserializer) deserializer); } else { return super.modifyCollectionDeserializer(config, type, beanDesc, deserializer); } } }); }}
There is no way to directly modify things in that way for array deserialization. But a relatively simple way may be to define a Converter
that takes Collection
(or List
) of expected type, returns the same, and use:
@JsonDeserialize(converter=MyConverter.class)
to indicate that it should be used as part of deserialization. What this would do is let Jackson deserialize Collection
using default logic, and then your converter can iterate through it and remove null
entries (or create a new Collection
if you prefer).
Alternatively you could create a custom Collection
/List
subtype, and override its add()
method to silently drop null
s, but pass other values via super.add(value)
. This would be the most efficient method, and perhaps even simplest.You could even declare property type to still be simple Collection
, but specify subtype to actually use with:
@JsonDeserialize(as=NoNullsCollection.class)public List<String> names;
You can configure your ObjectMapper to ignore NULLs like this:
ObjectMapper objectMapper = new ObjectMapper();objectMapper.setSerializationInclusion(Include.NON_NULL);
Or you can make use of the following annotation:
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)