以下技巧对我有用:
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"key1\": 1,\"key2\": null,\"key3\": 3}";
ConcurrentHashMap map = mapper.readValue(jsonString,new ConcurrentHashMap() {
@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}
我们的想法是简单地覆盖ConcurrentHashMap.put()方法,以便忽略要添加到地图的空值.
您可以创建自己的从ConcurrentHashMap扩展的类,而不是匿名内部类:
public class NullValuesIgnorerConcurrentHashMap
extends ConcurrentHashMap {
@Override
public V put(K key,V value) {
return value != null ? super.put(key,value) : null;
}
}
然后,您将使用此类反序列化为ConcurrentHashMap:
ConcurrentHashMap map =
mapper.readValue(jsonString,NullValuesIgnorerConcurrentHashMap.class);
System.out.println(map); // {key1=1,key3=3}
使用这种方法,返回的映射在给定空值时永远不会在put()上抛出NullPointerException.