简体   繁体   English

如何让Jackson忽略使用自定义KeyDeserializer反序列化失败的密钥?

[英]How can I get a Jackson to ignore a key that failed to deserialize with a custom KeyDeserializer?

I'm deserializing a Map with Jackson using a custom key deserializer that transforms the key before using it. 我正在使用自定义键反序列化器对Jackson进行反序列化,该自定义键反序列化器会在使用键之前对键进行转换。 I'd like to avoid null keys, so I'm trying to configure Jackson to just discard that entry and keep going, but I can't seem to find the right annotation. 我想避免使用空键,因此我试图将Jackson配置为仅丢弃该条目并继续进行,但是我似乎找不到正确的注释。 I annotating my map property with @JsonInclude , @JsonIgnoreProperties , and @JsonFilter with no luck. 我用@JsonInclude@JsonIgnoreProperties@JsonFilter注释了map属性, @JsonInclude没有运气。

ObjectMapper mapper = new ObjectMapper();

System.out.println(mapper.readValue("{ \"map\": { \"0\": \"zero\", \"1\": \"one\" } }", Test.class).map); // Works
System.out.println(mapper.readValue("{ \"map\": { \"0\": \"zero\", \"one\": \"one\" } }", Test.class).map); // Fails

Here's the class I'm deserializing: 这是我要反序列化的课程:

public class Test {
    @JsonDeserialize(keyUsing = StringIntKeyDeserializer.class, contentAs = String.class)
    public Map<Integer, String> map;
}

And my KeyDeserializer 还有我的KeyDeserializer

public class StringIntKeyDeserializer extends KeyDeserializer {
    @Override
    public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        try {
            return Integer.parseInt(key);
        } catch (NumberFormatException e) {
            throw ctxt.weirdKeyException(Integer.class, key, e.toString());
        }
    }
}

StringIntKeyDeserializer ,不引发异常,而返回null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM