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

Sha*_*vil 18 java polymorphism json jackson deserialization

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

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

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

{
    "type": "document",
    "properties": {
        "source": "foo",
        "proxy": "bar"
    }
}
Run Code Online (Sandbox Code Playgroud)

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

我在关闭的例子合作这篇文章,通读文档和问题,这里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]
Run Code Online (Sandbox Code Playgroud)

提前致谢!

解:

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

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

Mic*_*ber 19

你应该使用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 + "]";
    }
}
Run Code Online (Sandbox Code Playgroud)

另请参阅此问题中的答案:Jackson JsonTypeInfo.As.EXTERNAL_PROPERTY无法按预期工作.

  • 将注释添加到属性,而不是类......当然!太棒了,谢谢! (2认同)