我试图在杰克逊中实现多态反序列化,并试图使同一模型在两个地方都可以工作。
我有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
我了解错误,但不知道如何解决。我希望在两种情况下都可以使用相同的模型。这可能吗?
最佳答案
我自己才找到答案。应该只是添加了这个注释
关于java - 多态反序列化 jackson ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36226473/