我有一个 json 数据包,由一个 dacket 标头(在 PACKET_HEADER 下)+许多不同类型的消息(在 DATA 下)组成。这些消息具有相同的父类:
//my packet class
public class Packet {
public PacketHeader PACKET_HEADER;
public Message[] DATA;
}
//my parent message class:
public class Message {
public enum MessageType {
WHOAREYOU,
TimeData,
Ready,
LocationData
}
public MessageType getMessageType() {
return MESSAGE_TYPE;
}
public void setMessageType(MessageType MessageType) {
this.MESSAGE_TYPE = MessageType;
}
private MessageType MESSAGE_TYPE;
//declaring public for simplicity
public String SENDER;
public String SENDER_TYPE;
}
//sample child class:
public class TimeMessage extends Message {
private int tick;
public int getTick()
{
return tick;
}
我像这样反序列化输入:
@Override
public Handler create(Connector connector, Object packet, int clientID) {
Gson gson = new Gson();
Packet pack = gson.fromJson(packet.toString(), Packet.class);
System.out.println("Number of messages : " + pack.PACKET_HEADER.NOF_MESSAGES );//ok
for(Message msg : pack.DATA)
{
switch (msg.getMessageType()) {
//enters the switch successfully
case TimeData: {
System.out.println("Sender: " + msg.SENDER + " Sender_type: " + msg.SENDER_TYPE);//ok
TimeMessage time_msg = (TimeMessage) msg;//NOT ok, generates exception!!!!
//...
return new TimeHandler(time_msg, connector, clientID);
}
default:
System.out.println("Switch " + msg.getMessageType() + " is invalid");
return null;
}
}
return null;
}
你知道为什么我不能投到儿童班吗?我该如何解决。提前非常感谢。