[英]Ignore jackson deserialization if the data and model field are not of the same type
如果要反序列化的數據和 model 字段不是同一類型,我將如何忽略 Jackson 反序列化。
假設 Foo 是 model,我希望將數據反序列化為,數據如下所示:
public class Foo{
private boolean isTrue;
}
{
"isTrue": "ABC"
}
我知道@JsonIgnore
,但我需要一種更好的方法,如果要反序列化的數據與 model 數據類型本身匹配,則 Jackson 會反序列化數據。
也許您可以使用自定義反序列化器。 要確定數據是否可以反序列化為某種類型可能會很棘手,否則只是嘗試反序列化,如果失敗則返回一些默認值。 不好的是每種類型都需要一個自己的反序列化器,但我們可以在一定程度上對其進行抽象。
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.