Java:Jackson多态JSON反序列化具有接口属性的对象?
我使用Jackson的Java:Jackson多态JSON反序列化具有接口属性的对象?,java,json,jackson,deserialization,polymorphism,Java,Json,Jackson,Deserialization,Polymorphism,我使用Jackson的ObjectMapper来反序列化对象的JSON表示,该对象包含一个接口作为其属性之一。此处可以看到代码的简化版本: 基本上,我有一个类Asset,它有两个属性:type和properties。JSON模型如下所示: { "type": "document", "properties": { "source": "foo", "proxy": "bar" } } class Asset { @JsonTy
ObjectMapper
来反序列化对象的JSON表示,该对象包含一个接口作为其属性之一。此处可以看到代码的简化版本:
基本上,我有一个类Asset
,它有两个属性:type
和properties
。JSON模型如下所示:
{
"type": "document",
"properties": {
"source": "foo",
"proxy": "bar"
}
}
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 + "]";
}
}
properties
属性被定义为一个名为AssetProperties
的接口,我有几个类来实现它(例如DocumentAssetProperties
,ImageAssetProperties
)。其思想是图像文件与文档文件等具有不同的属性(高度、宽度)
我已经完成了中的示例,阅读了这里的文档和问题等等,并在@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,这需要一些谷歌搜索。以下是工作代码的更新要点:
您应该使用
JsonTypeInfo.As.EXTERNAL\u属性,而不是JsonTypeInfo.As.PROPERTY
。在此场景中,您的资产类应如下所示:
{
"type": "document",
"properties": {
"source": "foo",
"proxy": "bar"
}
}
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 + "]";
}
}
请参见我在这个问题中的回答:。将注释添加到属性,而不是类……当然!太棒了,谢谢你!现在,请为接口列表执行此操作……)您的POJO
s和JSON
是什么样子的?JSON输出是什么样子的?有很多嵌入的元数据吗?谢谢你链接到程序员Bruce的帖子。多好的资源啊