I’m using Spring Boot with the autoconfigured objectMapper.
Suppose I need to serialize and deserialize various HashMaps whose keys can be null. AFAIK this is not supported by default. So, how to do it most concisely?
The important part is that objectMapper needs to continue working as it does for every other type.
What I’ve tried already:
- For serialization, I added a custom NullKeySerializer which writes “null” string in case the map key is null (see below). Can it break other java types (not maps) during serializations? Also, maybe a bundled serializer exists somewhere? (I only found
com.fasterxml.jackson.datatype.jsr310.ser.key.Jsr310NullKeySerializer
but it’s marked as deprecated).
objectMapper.getSerializerProvider().setNullKeySerializer(new JsonSerializer<>() {
@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeFieldName("null");
}
});
- For deserialization, the only thing that I’ve found is to register a module with a custom deserializer.
Looks like you need to specify the return type in this case, so I’m not sure how to do it in case of generic maps (it can be Map<String, String> or Map<Integer, Object> – in any case, “null” string needs to be converted to the “real” null). Again, maybe there is an existing deserializer for this?
Note that I need to use the autoconfigured object mapper from Spring Boot and tune it if needed, so I would appreciate not having answers with new ObjectMapper()
or stuff like that. Also, I cannot use annotations like @JsonSerialize
on the specific fields, the whole configuration needs to be done in one place only.