The following trick has worked for me:
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"key1\": 1, \"key2\": null, \"key3\": 3}";
ConcurrentHashMap<String, Object> map = mapper.readValue(jsonString, new ConcurrentHashMap<String, Object>() {
@Override
public Object put(String key, Object value) {
return value != null ? super.put(key, value) : null;
}
}.getClass());
System.out.println(map); // {key1=1, key3=3}
The idea is to simply override ConcurrentHashMap.put()
method so that it ignores null
values that are to be added to the map.
Instead of an anonymous inner class, you could create your own class that extends from ConcurrentHashMap
:
public class NullValuesIgnorerConcurrentHashMap<K, V>
extends ConcurrentHashMap<K, V> {
@Override
public V put(K key, V value) {
return value != null ? super.put(key, value) : null;
}
}
Then you would use this class to deserialize to a ConcurrentHashMap
:
ConcurrentHashMap<String, Object> map =
mapper.readValue(jsonString, NullValuesIgnorerConcurrentHashMap.class);
System.out.println(map); // {key1=1, key3=3}
With this approach, the returned map would never throw NullPointerException
on put()
when given a null
value.