Java:Jackson具有接口属性的多态JSON反序列化对象?
我正在使用Jackson的ObjectMapper
来反序列化包含接口作为其属性之一的对象的JSON表示。 这里可以看到代码的简化版本:
https://gist.github.com/sscovil/8735923
基本上,我有一个具有两个属性的类Asset
: type
和properties
。 JSON模型如下所示:
{ "type": "document", "properties": { "source": "foo", "proxy": "bar" } }
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]
提前致谢!
解:
非常感谢@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无法按预期工作 。