I'm trying to deserialize a JSON string into a ConcurrentHashMap object and I'm getting errors because my JSON contains properties with null values, but ConcurrentHashMap does not accept null values. Here is the fragment of code:
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(jsonString, ConcurrentHashMap.class);
Is there a way to ignore properties with null values during deserialization? I know that we can ignore these properties during serialization:
mapper.setSerializationInclusion(JsonInclude.NON_NULL);
But what about deserialization process?
In order to ignore null fields at the class level, we use the @JsonInclude annotation with include. NON_NULL.
To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.
Overview So when Jackson is reading from JSON string, it will read the property and put into the target object. But when Jackson attempts to serialize the object, it will ignore the property. For this purpose, we'll use @JsonIgnore and @JsonIgnoreProperties.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With