如果数据和模型字段不是同一类型,则忽略 jackson 反序列化

Ignore jackson deserialization if the data and model field are not of the same type

如果要反序列化的数据和模型字段的类型不同,我将如何忽略 Jackson 反序列化。

假设 Foo 是我要反序列化数据的模型,数据如下:

public class Foo{
    private boolean isTrue;
}
{
    "isTrue": "ABC"
}

我知道 @JsonIgnore,但如果要反序列化的数据本身与模型数据类型匹配,我需要一种更好的方法让 Jackson 反序列化数据。

也许您可以使用自定义解串器。找出数据是否可以反序列化为某种类型可能很棘手,而不是仅仅尝试反序列化,如果失败则 return 一些默认值。不好的是每种类型都需要一个自己的反序列化器,但我们可以在某种程度上对其进行抽象。

public static abstract class SafeDeserializer<T> extends JsonDeserializer<T> {
    protected abstract Class<T> getClassT();

    // This is just fine for any other than primitives.
    // Primitives like boolean cannot be set to null so there is a need for 
    // some default value, so override.
    protected T getDefaultValue() {
        return null;
    }

    @Override
    public T deserialize(JsonParser p, DeserializationContext ctxt)
                            throws IOException, JsonProcessingException {
        try {
            return (T) ctxt.readValue(p, getClassT());
        } catch (MismatchedInputException e) {
            return getDefaultValue();
        }
    }
}

现在扩展它来处理一个坏的 boolean 会是这样的:

public static class SafeBooleanDeserializer extends SafeDeserializer<Boolean> {
    @Getter
    private final Class<Boolean> classT = Boolean.class;

    // This is needed only because your class has primitive boolean
    // If it was a boxed Boolean null would be fine.
    @Override
    protected Boolean getDefaultValue() {
        return false;
    }
}

休息很简单,像这样注释您的字段:

@JsonDeserialize(using = SafeBooleanDeserializer.class)
private boolean isTrue;