如果要反序列化的数据和模型字段不是同一类型,我如何忽略Jackson反序列化?
假设Foo是我想要将数据反序列化到的模型,数据如下:
public class Foo{
private boolean isTrue;
}{
"isTrue": "ABC"
}我知道@JsonIgnore,但我需要一种更好的方法,如果要反序列化的数据本身与模型数据类型匹配,那么Jackson就可以反序列化数据。
发布于 2020-12-01 02:55:38
也许你可以使用定制的反序列化程序。要找出数据是否可以反序列化为某种类型可能很棘手,而不仅仅是尝试反序列化,如果反序列化失败,则返回一些默认值。糟糕的是,每种类型都需要自己的反序列化程序,但我们可以在某种程度上对其进行抽象。
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;
}
}Rest非常简单,像这样注释你的字段:
@JsonDeserialize(using = SafeBooleanDeserializer.class)
private boolean isTrue;https://stackoverflow.com/questions/65075620
复制相似问题