小编典典

Java:具有接口属性的对象的Jackson多态JSON反序列化吗?

json

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

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

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

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

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

我在工作过的例子这篇文章,通读文档和问题,这里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,我得以解决此问题。我还能够将枚举用作类型ID,这需要花点时间进行谷歌搜索。这是带有工作代码的更新的Gist:

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


阅读 358

收藏
2020-07-27

共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 + "]";
    }
}
2020-07-27