简体   繁体   中英

Ignore JsonDeserializer when deserialising sub classes objects

I have parent class on which I have specified a custom deserialiser like this -

@JsonDeserialize(using = CustomDeserializer.class)
public class ParentClass {
}

I have subclasses extending above class and I don't want those classes to use CustomDeserializer for deserialisation purpose. I know using Will ignore the CustomDeserializer class during serialisation.

@JsonDeserialize(as = Child.class)
public class ChildClass extends ParentClass {
}

The question is - Is there any other way to tell ObjectMapper or anything else which will ignore this CustomDeserializer without specifically specifying @JsonDeserialize(as = Child.class) on every child class ?

Remove the annotation from the ParentClass and create a new subclass with the annotation. Use this new subclass when you want to deserialize to a ParentClass. As the custom deserialize annotation is on the subclass you can return an instance of ParentClass.

public class ParentClass {
    // fields in the ParentClass
}

@JsonDeserialize(using = CustomDeserializer.class)
public class ParentWithCustomDeserialize extends Parent {
}

Then you can simply...

Parent parent = objectMapper.readValue(jsonString, ParentWithCustomDeserialize.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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