【问题标题】:Parse to a Subclass by default with Jackson默认情况下使用 Jackson 解析为子类
【发布时间】:2014-12-16 13:55:41
【问题描述】:

我有一个名为 Product 的类和一些扩展它的子类。现在在我的注释中我有很多类型,像这样:

@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes({@Type(value=RoomProduct.class, name="RoomProduct"),
           @Type(value=GroundProduct.class, name="GroundProduct"),
           })

然后是我的 Product 类的定义。我想要做的是,如果杰克逊无法检测到该字段不符合任何这些结构,则返回一个

未知产品

如何使用 Jackson @Type 注释来做到这一点?它应该类似于在名称中添加空白或在值中添加一些我不知道的标志(我尝试创建扩展 Product 的 UnknownProduct 并且在名称值中没有任何内容但没有成功。

【问题讨论】:

    标签: java jackson subtype


    【解决方案1】:

    @JsonTypeInfo 有一个指定默认实现类的选项,但经过一些调试后,我发现 WrapperObject 的“defaultImpl”已损坏。配置:

    @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include= JsonTypeInfo.As.WRAPPER_OBJECT, defaultImpl = UnknownProduct.class)
    

    杰克逊实现(AsWrapperTypeDeserializer):

    public AsWrapperTypeDeserializer(JavaType bt, TypeIdResolver idRes,
            String typePropertyName, boolean typeIdVisible, Class<?> defaultImpl)
    {
        super(bt, idRes, typePropertyName, typeIdVisible, null);
    }
    

    请注意,'defaultImpl' 被传递,但它被忽略并且配置的默认类将不会被使用。我在 jackson 的 Jira 中没有找到此问题的记录票。

    这只是 WRAPPER_OBJECT 的问题,defaultImpl 对其他格式工作正常。但它会改变 JSON 格式。如果你可以改变它——你可以使用 EXTERNAL_PROPERTY 例如默认实现:

    @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include= JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "type", defaultImpl = UnknownProduct.class)
    

    另一种解决方案: 如果您必须使用 WRAPPER_OBJECT,那么您可以配置 Jackson 在找到未知子类型时不会失败:

    objectMapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
    

    这与您所要求的并不完全相同,但在这种情况下,您的产品将为空。也许您可以将 null 视为未知产品。

    更新 我已经提交了一个 Jackson 错误:https://github.com/FasterXML/jackson-databind/issues/656

    更新此票已针对 2.3 和 2.4 jackson 解决,希望您很快能够在将 jar 重新安装到 maven 存储库或新版本中时使用它。

    【讨论】:

    • 不是我想要的,虽然我试过了,但仍然得到 JsonMappingException。我知道你可以在@JsonTypeInfo 中设置一个defaultImpl,但我无法让它工作,我的标题是:@JsonTypeInfo(use=JsonTypeInfo.Id.NAME,include=JsonTypeInfo.As.WRAPPER_OBJECT,defaultImpl=未知产品.class)。谢谢伊利亚!
    • 它正在我的测试应用程序上工作:没有 JsonMappingException 并且 Project 被解析为 null。如果您发布 Product、RoomProduct、GroundProduct 和您进行序列化/反序列化的类——我可以看看
    • 我发现 WRAPPER_OBJECT 有一个忽略 defaultImpl 类的错误。请查看更新后的解决方案。
    • @StaxMan 这是我今天在 Jackson Jira 创建的一张票。不知道你想说什么。
    • 啊抱歉,没有注意到您上面的更新(打开了旧版本)说明了我的意思。 :)
    猜你喜欢
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 2016-04-14
    • 2010-12-02
    • 2012-11-24
    • 1970-01-01
    相关资源
    最近更新 更多