【问题标题】:Polymorphic deserialization jackson多态反序列化杰克逊
【发布时间】: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)
  • 是的,我知道...但我希望找到一种方法,在两种情况下都使用相同的模型。

标签: java android json jackson


【解决方案1】:

刚刚自己找到了答案。应该简单地添加这个注释

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

【讨论】:

  • 你拯救了我的一天
猜你喜欢
  • 2015-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-13
  • 2012-12-22
  • 1970-01-01
  • 2015-04-07
  • 1970-01-01
相关资源
最近更新 更多