jackson java网络接口,Java:Jackson具有接口属性的多态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:

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"

}

}

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.

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]

Thanks in advance!

SOLUTION:

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:

解决方案

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 + "]";

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值