问题描述
我正在使用Jackson的 ObjectMapper
来反序列化包含接口作为其属性之一的对象的JSON表示。这里可以看到代码的简化版本:
I am using Jackson's ObjectMapper
to deserialize a JSON representation of an object that contains an interface as one of its properties. A simplified version of the code can be seen here:
基本上,我有一个类资产
有两个属性:键入
和属性
。 JSON模型如下所示:
Basically, I have a class Asset
with two properties: type
and properties
. The JSON model looks like this:
{
"type": "document",
"properties": {
"source": "foo",
"proxy": "bar"
}
}
属性
属性定义为名为 AssetProperties ,我有几个实现它的类(例如
DocumentAssetProperties
, ImageAssetProperties
)。这个想法是图像文件具有与文档文件不同的属性(高度,宽度)等。
The
properties
property is defined as an interface called AssetProperties
, and I have several classes that implement it (e.g. DocumentAssetProperties
, ImageAssetProperties
). The idea is that image files have different properties (height, width) than document files, etc.
我已经在,阅读有关SO及更高版本的文档和问题,并尝试使用不同的配置
@JsonTypeInfo
注释参数,但未能破解这个坚果。任何帮助将不胜感激。
I've worked off of the examples in this article, read through docs and questions here on SO and beyond, and experimented with different configurations in the
@JsonTypeInfo
annotation parameters, but haven't been able to crack this nut. Any help would be greatly appreciated.
最近,我得到的例外是:
Most recently, the exception I'm getting is this:
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,包含工作代码:
With many thanks to @Michał Ziober, I was able to resolve this issue. I was also able to use an Enum as a type id, which took a bit of Googling. Here is an updated Gist with working code:
推荐答案
你应该使用
JsonTypeInfo.As.EXTERNAL_PROPERTY
而不是 JsonTypeInfo.As.PROPERTY
。在这种情况下,您的资产
类应如下所示:
You should use
JsonTypeInfo.As.EXTERNAL_PROPERTY
instead of JsonTypeInfo.As.PROPERTY
. In this scenario your Asset
class should look like this:
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无法按预期工作。
See also my answer in this question: Jackson JsonTypeInfo.As.EXTERNAL_PROPERTY doesn't work as expected.
这篇关于Java:Jackson具有接口属性的多态JSON反序列化对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!