Jackson – 如何为接口引用的反序列化指定单个实现?

我想用Jackson反序列化JSON-Object。 因为目标是一个接口,我需要指定应该使用哪个实现。

可以使用@JsonTypeInfo-Annotation将此信息存储在JSON-Object中。 但是我想在源代码中指定实现,因为它始终是相同的。

这可能吗?

使用SimpleAbstractTypeResolver :

ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule("CustomModel", Version.unknownVersion()); SimpleAbstractTypeResolver resolver = new SimpleAbstractTypeResolver(); resolver.addMapping(Interface.class, Implementation.class); module.setAbstractTypes(resolver); mapper.registerModule(module); 

如果您只有单个接口实现,还有另一种方法可行。

 public class ClassYouWantToDeserialize { @JsonDeserialize(as = ImplementationClass.class) private InterfaceClass property; ... } 

这个问题很久以前就得到了回答,但我想给你另一个选项,它不需要调整ObjectMapper,也比@JsonTypeInfo注释简单得多。

您也可以在接口上使用@JsonDeserialize(as = ImplementationClass.class) ,并且所有引用都将以相同的方式反序列化。

注意,如果你的一个实现类是一个枚举,你也可能需要在枚举上使用@JsonFormat(shape = JsonFormat.Shape.OBJECT)