杰克逊 - 自定义TypeId解析器

时间:2016-01-15 15:39:05

标签: java jackson

我一直在为我的一个班级使用自定义typeId解析器,到目前为止,我一直专注于注释支持:

@JsonTypeInfo(
    use = JsonTypeInfo.Id.CUSTOM,
    include = JsonTypeInfo.As.PROPERTY,
    property = "@type")
@JsonTypeIdResolver(ColumnDefinitionTypeResolver.class)

但是现在我需要通过构造函数或setter将一些其他依赖项传递给它来自定义类型解析器的创建,并且由于Jackson是实例化它的人,我无法找到解决方法。

有没有办法配置ObjectMapper以使用TypeIdResolver而不是依赖注释?

此致

2 个答案:

答案 0 :(得分:2)

所以你有两个选择:

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"; 创建您提供的类型的实例。目前无法将其配置为其他方式。

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);

2)创建一个模块来处理类型和子类型的反序列化。

streakTemp = orig(:, maskD(1,:) == 1);

有关更详细的示例,请参阅杰克逊文档How-To: Custom Deserializers

答案 1 :(得分:0)

您还可以通过编程方式设置自定义类型ID解析程序。查看最上面的答案here。 寻找这行:

typeResolver.init(JsonTypeInfo.Id.CLASS, null);

用类型ID解析器替换null

相关问题