The following trick 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);
The idea is to simply override the ConcurrentHashMap.put() method so that it ignores the null values that must be added to the map.
Instead of an anonymous inner class, you can create your own class, which 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 should use this class to deserialize in ConcurrentHashMap :
ConcurrentHashMap<String, Object> map = mapper.readValue(jsonString, NullValuesIgnorerConcurrentHashMap.class); System.out.println(map);
With this approach, the returned map never throws a NullPointerException on put() when set to null .
Federico peralta schaffner
source share