繁体   English   中英

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

[英]Java: Jackson polymorphic JSON deserialization of an object with an interface property?

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

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

基本上,我有一个具有两个属性的类Assettypeproperties 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,我能够解决这个问题。 我还能够使用Enum作为类型ID,这需要一些谷歌搜索。 这是一个带有工作代码的更新Gist:

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

您应该使用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无法按预期工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM