【发布时间】:2016-03-25 19:17:45
【问题描述】:
我正在尝试在 jackson 中实现多态反序列化,并尝试使相同的模型在两个地方工作。
我有 ShopData 对象
public class ShopData extends Embeddable implements Serializable
{
private final int id;
private final String name;
private final String logoImageUrl;
private final String heroImageUrl;
public ShopData(@JsonProperty(value = "id", required = true) int id,
@JsonProperty(value = "name", required = true) String name,
@JsonProperty(value = "logoImageUrl", required = true) String logoImageUrl,
@JsonProperty(value = "heroImageUrl", required = true) String heroImageUrl)
{
this.id = id;
this.name = name;
this.logoImageUrl = logoImageUrl;
this.heroImageUrl = heroImageUrl;
}
}
我的可嵌入对象如下所示
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes({@JsonSubTypes.Type(value = AnotherObject.class, name = "AnotherObject"),
@JsonSubTypes.Type(value = ShopData.class, name = "shop")
})
public abstract class Embeddable
{
}
我试图让这个模型在两个地方工作。此模型按预期工作。
public Order(@JsonProperty(value = "_embedded", required = true) Embeddable embedded)
{
this.embedded = (ShopData) embedded;
}
"_embedded": {
"shop": {
"id": 1,
"name": "",
"freshItems": 5,
"logoImageUrl": "",
"heroImageUrl": "",
"_links": {
"self": {
"href": "/shops/1"
}
}
}
虽然没有
public ShopList(@JsonProperty(value = "entries", required = true) List<ShopData> entries)
{
this.entries = Collections.unmodifiableList(entries);
}
{
"entries": [
{
"id": 1,
"name": "",
"freshItems": 5,
"logoImageUrl": "",
"heroImageUrl": "",
"_links": {
"self": {
"href": "/shops/1"
}
}
}
]
}
并抛出错误:Could not resolve type id 'id' into a subtype
我了解该错误,但不知道如何解决。我希望能够在这两种情况下使用相同的模型。这可能吗?
【问题讨论】:
-
我认为问题在于 ShopData 列表想要这样的 json:
[{"shop": {...}}, {"shop": {...}}, {"shop": {...}}]因为ShopData固有Embeddable行为@JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT) -
是的,我知道...但我希望找到一种方法,在两种情况下都使用相同的模型。