2016-03-25 172 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