【问题标题】:Java: Jackson polymorphic JSON deserialization of an object with an interface property?Java:具有接口属性的对象的杰克逊多态 JSON 反序列化?
【发布时间】:2014-01-31 17:08:13
【问题描述】:

我正在使用 Jackson 的 ObjectMapper 反序列化包含接口作为其属性之一的对象的 JSON 表示。代码的简化版本可以在这里看到:

https://gist.github.com/sscovil/8735923

基本上,我有一个类Asset 有两个属性:typeproperties。 JSON 模型如下所示:

{
    "type": "document",
    "properties": {
        "source": "foo",
        "proxy": "bar"
    }
}

properties 属性被定义为一个名为AssetProperties 的接口,我有几个实现它的类(例如DocumentAssetPropertiesImageAssetProperties)。这个想法是图像文件具有与文档文件等不同的属性(高度、宽度)。

我已经处理了this article 中的示例,阅读了有关 SO 及其他内容的文档和问题,并在 @JsonTypeInfo 注释参数中尝试了不同的配置,但一直无法破解这个难题.任何帮助将不胜感激。

最近,我得到的例外是:

java.lang.AssertionError: Could not deserialize JSON.
...
Caused by: org.codehaus.jackson.map.JsonMappingException: Could not resolve type id 'source' into a subtype of [simple type, class AssetProperties]

提前致谢!

解决方案:

非常感谢@Michał Ziober,我能够解决这个问题。我还可以使用 Enum 作为类型 id,这需要一些谷歌搜索。这是一个更新的 Gist 和工作代码:

https://gist.github.com/sscovil/8788339

【问题讨论】:

  • Json 输出看起来像这样的东西是什么?有一堆嵌入的元数据吗?
  • 感谢程序员布鲁斯帖子的链接。多么棒的资源

标签: java json jackson deserialization polymorphism


【解决方案1】:

您应该使用JsonTypeInfo.As.EXTERNAL_PROPERTY 而不是JsonTypeInfo.As.PROPERTY。在这种情况下,您的 Asset 类应如下所示:

class Asset {

    @JsonTypeInfo(
            use = JsonTypeInfo.Id.NAME,
            include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
            property = "type")
    @JsonSubTypes({
        @JsonSubTypes.Type(value = ImageAssetProperties.class, name = "image"),
        @JsonSubTypes.Type(value = DocumentAssetProperties.class, name = "document") })
    private AssetProperties properties;

    public AssetProperties getProperties() {
        return properties;
    }

    public void setProperties(AssetProperties properties) {
        this.properties = properties;
    }

    @Override
    public String toString() {
        return "Asset [properties("+properties.getClass().getSimpleName()+")=" + properties + "]";
    }
}

另请参阅我对这个问题的回答:Jackson JsonTypeInfo.As.EXTERNAL_PROPERTY doesn't work as expected

【讨论】:

  • 将注释添加到属性,而不是类...当然!太棒了,谢谢!
  • 现在请做一个接口列表。 ... :)
  • 你的 POJOs 和 JSON 看起来怎么样?
猜你喜欢
  • 1970-01-01
  • 2018-03-03
  • 2013-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-13
  • 1970-01-01
相关资源
最近更新 更多