我一直在为我的一个类使用自定义 typeId 解析器,到目前为止我一直依赖注释支持:
@JsonTypeInfo(
use = JsonTypeInfo.Id.CUSTOM,
include = JsonTypeInfo.As.PROPERTY,
property = "@type")
@JsonTypeIdResolver(ColumnDefinitionTypeResolver.class)
但现在我需要通过构造函数或 setter 将一些其他依赖项传递给它来自定义类型解析器的创建,并且由于 Jackson 是实例化它的人,我找不到绕过它的方法。
有没有办法将 ObjectMapper 配置为使用 TypeIdResolver 而不是依赖注释?
问候
最佳答案
所以你有两个选择:
1) 如果您设置为使用 @JsonTypeIdResolver
,您将在 TypeIdResolver
中使用 static
状态。这可能不是您想要的。
默认的 JacksonAnnotationIntrospector
将尝试根据其默认构造函数使用 JsonTypeIdResolver
创建您提供的类型的实例。目前无法配置它以执行其他操作。
public final class ColumnDefinitionTypeResolver implements TypeIdResolver {
// You could rely on static state.
public static String SOME_ACCESSIBLE_OBJECT = null;
public ColumnDefinitionTypeResolver() {
// This is what gets called.
}
}
ColumnDefinitionTypeResolver.SOME_ACCESSIBLE_OBJECT = "I can affect the implementation from here, but using static state ... be careful";
2) 创建一个模块来处理您的类型和子类型的反序列化。
SimpleModule columnDefinitionModule = new SimpleModule("colDefMod", new Version(1, 0, 0, null))
.addDeserializer(ColumnDefinition.class, new JsonDeserializer() {
@Override
public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
// Need to read the type out and then use ObjectMapper to deserialize using the correct token
}
})
.registerSubtypes(...); // add your subtypes here.
(new ObjectMapper()).registerModule(columnDefinitionModule);
有关更详细的示例,请参阅 Jackson 文档 How-To: Custom Deserializers .
关于java - Jackson - 自定义 TypeId 解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34814664/