我正在尝试将JSON字符串反序列化为ConcurrentHashMap对象,并且我收到错误,因为我的JSON包含具有空值的属性,但ConcurrentHashMap不接受空值.这是代码片段:
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(jsonString, ConcurrentHashMap.class);
Run Code Online (Sandbox Code Playgroud)
有没有办法在反序列化期间忽略具有空值的属性?我知道在序列化过程中我们可以忽略这些属性:
mapper.setSerializationInclusion(JsonInclude.NON_NULL);
Run Code Online (Sandbox Code Playgroud)
但是反序列化过程呢?
以下技巧对我有用:
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}
Run Code Online (Sandbox Code Playgroud)
这个想法是简单地重写ConcurrentHashMap.put()方法,以便它忽略null要添加到映射中的值。
您可以创建自己的类,该类扩展自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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后您将使用此类反序列化为ConcurrentHashMap:
ConcurrentHashMap<String, Object> map =
mapper.readValue(jsonString, NullValuesIgnorerConcurrentHashMap.class);
System.out.println(map); // {key1=1, key3=3}
Run Code Online (Sandbox Code Playgroud)
通过这种方法,返回的映射在给定值时永远不会NullPointerException抛出。put()null