簡體   English   中英

多態反序列化jackson

[英]Polymorphic deserialization jackson

我正在嘗試在 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;
    }
}

我的 Embeddable 對象看起來像這樣

@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

我了解錯誤,但不知道如何解決此問題。 我希望能夠在兩種情況下使用相同的模型。 這可能嗎?

剛剛自己找到了答案。 應該簡單地添加這個注釋

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM