Java – how to ignore attributes with null values during deserialization from JSON

I am trying to deserialize a JSON string into a concurrenthashmap object, and I receive an error because my JSON contains properties with null values, but concurrenthashmap does not accept null values This is a code snippet:

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

Is there any way to ignore attributes with null values during deserialization? I know we can ignore these attributes during serialization:

mapper.setSerializationInclusion(JsonInclude.NON_NULL);

But what about the deserialization process?

Solution

The following tips have 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}

Our idea is to simply override concurrenthashmap Put () method to ignore null values to be added to the map

Instead of anonymous inner classes, you can create your own classes that extend 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;
    }
}

You will then use this class to deserialize to concurrenthashmap:

ConcurrentHashMap<String,Object> map = 
    mapper.readValue(jsonString,NullValuesIgnorerConcurrentHashMap.class);

System.out.println(map); // {key1=1,key3=3}

Using this method, the returned map will never throw a NullPointerException on put () given a null value

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>