2016-03-25 132 views
1

我想在杰克逊实现多态反序列化并试图在两个地方做同样的模型工作。多态反序列化杰克逊

我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

我理解的错误,但不知道如何解决这个问题。我希望能够在这两种情况下使用相同的模型。这可能吗?

+0

我想问题是ShopData列表想要这样的json:'[{“shop”:{...}},{“shop”:{...}}, {“shop”:{...}}]'因为'ShopData'内嵌'Embeddable'行为'@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,include = JsonTypeInfo.As.WRAPPER_OBJECT)' – varren

+0

是的,我知道......但我希望找到一种在两种情况下简单使用相同模型的方法。 – Datenshi

回答

1

我自己找出答案。应该简单地加上这个加号

@JsonTypeInfo(use= JsonTypeInfo.Id.NONE) 
public class ShopData extends Embeddable implements Serializable 
@JsonTypeInfo(use= JsonTypeInfo.Id.NONE) 
public class ShopData extends Embeddable implements Serializable 
+0

你节省了我的一天 – akuma8