[英]Jackson - How to specify a single implementation for interface-referenced deserialization?
I want to deserialize a JSON-Object with Jackson.我想用 Jackson 反序列化一个 JSON 对象。 Because the target is an interface I need to specify which implementation should be used.
因为目标是一个接口,所以我需要指定应该使用哪个实现。
This information could be stored in the JSON-Object, using @JsonTypeInfo-Annotation.可以使用 @JsonTypeInfo-Annotation 将此信息存储在 JSON-Object 中。 But I want to specify the implementation in source code because it's always the same.
但我想在源代码中指定实现,因为它总是相同的。
Is this possible?这可能吗?
Use a SimpleAbstractTypeResolver :使用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);
There is another approach that will work if you have just single interface implementation.如果您只有单个接口实现,还有另一种方法可以工作。
public class ClassYouWantToDeserialize {
@JsonDeserialize(as = ImplementationClass.class)
private InterfaceClass property;
...
}
This question was answered a while ago but I want to give you another option that doesn't require to tune ObjectMapper and also much simpler then @JsonTypeInfo annotation.这个问题是在不久前回答的,但我想给你另一个不需要调整 ObjectMapper 并且比 @JsonTypeInfo 注释简单得多的选项。
You can use @JsonDeserialize(as = ImplementationClass.class)
on the interface as well and all references will be deserialized the same way.您也可以在接口上使用
@JsonDeserialize(as = ImplementationClass.class)
并且所有引用都将以相同的方式反序列化。
Note, if one of your Implementation classes is an enum, you might need @JsonFormat(shape = JsonFormat.Shape.OBJECT)
on the enum as well.请注意,如果您的实现类之一是枚举,则您可能还需要在枚举上使用
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.