How to ignore properties with empty values ​​during deserialization from JSON

I am trying to deserialize a JSON string into a ConcurrentHashMap object and I am getting errors because my JSON contains properties with null values, but ConcurrentHashMap does not accept null values. Here is the code snippet:

ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(jsonString, ConcurrentHashMap.class); 

Is there a way to ignore null-value properties during deserialization? I know that we can ignore these properties during serialization:

 mapper.setSerializationInclusion(JsonInclude.NON_NULL); 

But what about the deserialization process?

+7
java json jackson
source share
2 answers

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); // {key1=1, key3=3} 

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); // {key1=1, key3=3} 

With this approach, the returned map never throws a NullPointerException on put() when set to null .

+1
source share

There may be a better way, but a workaround would be:

 Map<String, Object> map = mapper.readValue(jsonString, HashMap.class); map.values().removeIf(o -> o == null); return new ConcurrentHashMap<> (map); 
+3
source share

All Articles