我正在使用杰克逊的ObjectMapper
反序列化包含接口作为其属性之一的对象的 JSON 表示形式。代码的简化版本可以在这里看到:
https://gist.github.com/sscovil/8735923
基本上,我有一个班级Asset
有两个属性:type
and properties
。 JSON 模型如下所示:
{
"type": "document",
"properties": {
"source": "foo",
"proxy": "bar"
}
}
The 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,我能够解决这个问题。我还可以使用枚举作为类型 ID,这需要一些谷歌搜索。这是带有工作代码的更新要点:
https://gist.github.com/sscovil/8788339