序列化后在超类列表中转换继承的类

时间:2016-04-20 17:08:11

标签: java android spring rest inheritance

我目前正与几位同学一起开发一款安卓游戏。这是对纸牌等的棋盘游戏的改编。我们有一个服务器和一个客户端,通信与Spring Boot一起工作。

我遇到了关于列表元素的转换问题。我们有一个牌组(ArrayList< Card>),我们有多种类型的牌,让我们说明牌(枪中留下不同的子弹)和牌照。 BulletCard和ShootCard都继承自Card。

如果我将卡添加到我的ArrayList<卡>,我可以将它们转发回继承的类,在服务器端没有任何问题。但是如果客户端获得了ArrayList,则无法进行转换,因为我丢失了子类的信息(示例中的bulletcounter)。

有没有办法可以传输这些数据?

ArrayList<Card> handcardDeck= new ArrayList<>();

handcardDeck.add(new ShootCard());
BulletCard bulletCard = new BulletCard();
bulletCard.setBulletCounter(3);
handcardDeck.add(bulletCard);

ShootCard s = (ShootCard) handcardDeck.get(0);
BulletCard b = (BulletCard) handcardDeck.get(1);
Integer i = b.getBulletCounter();

Rest-Output看起来像这样:

 "cards": [
      {
        "id": 26
      },
      {
        "id": 28
      },
      {
        "id": 29
      },
      {
        "id": 32
      }

如果我创造一个纯粹的&#34; bulletsdeck(ArrayList&lt; BulletCard&gt;)我明白了。

    "cards": [
      {
        "id": 17,
        "bulletCounter": 1
      },
      {
        "id": 18,
        "bulletCounter": 2
      },
      {
        "id": 19,
        "bulletCounter": 3
      }]

我可以以某种方式获得#1中列表中所有子弹卡的#2输出吗?

1 个答案:

答案 0 :(得分:0)

所以我找到了解决方案:

在父类中定义@JsonTypeInfo和@JsonSubTypes就可以了。

import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo; 

@Entity
@JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
@JsonSubTypes({
        @JsonSubTypes.Type(ShootCard.class),
        @JsonSubTypes.Type(BulletCard.class)
})

public class Card implements Serializable {}

http://www.studytrails.com/java/json/java-jackson-Serialization-polymorphism.jsp