Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore properties with empty values during deserialization from JSON

Tags:

java

json

jackson

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?

like image 906
Radu Dumbrăveanu Avatar asked Aug 28 '15 11:08

Radu Dumbrăveanu


People also ask

How do I ignore empty values in JSON response?

In order to ignore null fields at the class level, we use the @JsonInclude annotation with include. NON_NULL.

How do I ignore properties in JSON?

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.

How do you tell Jackson to ignore a field during deserialization?

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.


1 Answers

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);
like image 106
assylias Avatar answered Oct 24 '22 19:10

assylias