Jackson custom KeyDeserializer for Map, excluding entries where key is null

♀尐吖头ヾ 提交于 2021-02-10 18:34:00

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!