我一直在为我的一个类使用自定义 typeId 解析器,到目前为止,我一直依赖于注释支持:
@JsonTypeInfo(
use = JsonTypeInfo.Id.CUSTOM,
include = JsonTypeInfo.As.PROPERTY,
property = "@type")
@JsonTypeIdResolver(ColumnDefinitionTypeResolver.class)
Run Code Online (Sandbox Code Playgroud)
但是现在我需要通过构造函数或 setter 将一些其他依赖项传递给类型解析器来自定义类型解析器的创建,并且由于 Jackson 是实例化它的人,因此我找不到解决方法。
有没有办法将 ObjectMapper 配置为使用 TypeIdResolver 而不是依赖注释?
问候
所以你有两个选择:
1)如果你在使用设置@JsonTypeIdResolver您的卡使用static在您的状态TypeIdResolver。这可能不是你想要的。
默认值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";
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
有关更详细的示例,请参阅 Jackson 文档How-To: Custom Deserializers。
| 归档时间: |
|
| 查看次数: |
9187 次 |
| 最近记录: |