用于地图的Jackson自定义KeyDeserializer,不包括key为null的条目 [英] Jackson custom KeyDeserializer for Map, excluding entries where key is null
问题描述
我的POJO中的自定义密钥反序列化器如下:
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.
例如,如果用于接受键 AGE
和 HEIGHT
的代码并且想开始排除 HEIGHT
,则JSON对象 {"AGE":30,"HEIGHT":60}
将反序列化为地图中的 {"AGE":30}
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
我尝试解决此问题的方法是从 MyCustomKeyDeserializer
类返回一个 null
值.但是,该地图现在最终以包含 null
作为键之一的条目结尾.有没有办法从地图中排除空键?还是提供这种行为的另一种方法?
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);
}
}
推荐答案
如果知道键名是什么,则可以使用 com.fasterxml.jackson.annotation.JsonIgnoreProperties
批注:
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;
这篇关于用于地图的Jackson自定义KeyDeserializer,不包括key为null的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!