问题
The custom key deserializer in my POJO as follows:
@JsonDeserialize(keyUsing = MyCustomKeyDeserializer.class)
@JsonInclude
private Map<T, @Range(min = 0, max = 100) Integer> ratios;
However, I have a situation where a key that was previously valid, is no longer valid and would like to offer backward compatibility.
For example, if the code used to accept the keys AGE
and HEIGHT
and would like to start excluding HEIGHT
, the JSON object {"AGE": 30, "HEIGHT": 60}
would be deserialized to just {"AGE": 30}
in the map
The way I tried to approach it was by returning a null
value from the MyCustomKeyDeserializer
class. However, the map is now ending up with an entry containing null
as one of the keys. Is there a way to exclude null keys from the map? Or a different approach to providing such behavior?
The code for the serializer is along the lines as follows:
public class MyCustomKeyDeserializer extends KeyDeserializer {
private Map<String, Object> registry;
@Override
public Object deserializeKey(final String key, final DeserializationContext ctxt)
throws IOException {
return registry.get(key);
}
}
回答1:
If you know what is the key name is, you can just use com.fasterxml.jackson.annotation.JsonIgnoreProperties
annotation:
@JsonIgnoreProperties(value = {"HEIGHT"})
@JsonDeserialize(keyUsing = MyCustomKeyDeserializer.class)
private Map<T, @Range(min = 0, max = 100) Integer> ratios;
来源:https://stackoverflow.com/questions/59569992/jackson-custom-keydeserializer-for-map-excluding-entries-where-key-is-null