访问JSON多态POJO类

时间:2016-06-10 14:25:04

标签: java json spring jackson pojo

我收集了其他人写的代码,而且我很难理解如何访问子类。

父类:

package blah.blah.blah;

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

import java.io.Serializable;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "type")
@JsonSubTypes({
    @JsonSubTypes.Type(value = EmailMessage.class, name = "Email"),
    @JsonSubTypes.Type(value = SMSMessage.class, name = "SMS")
})    
public class Message implements Serializable {

   private static final long serialVersionUID = 1L;

   private String messageBody;

   public String getMessageBody() {
      return messageBody;
   }
   public void setMessageBody(String messageBody) {
      this.messageBody = messageBody;
   }
}

儿童班:

package blah.blah.blah;

public class EmailMessage extends Message {
   private String subject;

   public String getSubject() {
       return subject;
   }
   public void setSubject(String subject) {
       this.subject = subject;
   }
}

儿童班:

package blah.blah.blah;

public class SMSMessage extends Message {
}

我有一个从JSON消息映射的Message实例,但我无法弄清楚如何访问' Type'字段以及如何访问'主题'字段(如果它是电子邮件)。

JSON:

"messageList": [{
    "type": "Email",
    "messageBody": "Email body",
    "subject": "Email subject"
}, {
    "type": "SMS",
    "messageBody": "SMS body"
}]

我尝试过的事情:

Message incomingMessage = messageList.getMessageList().get(0);
log.info("Message Body: " + incomingMessage.getMessageBody());

1 个答案:

答案 0 :(得分:1)

感谢@ cricket_007和@zapl在评论中的答案。随意写这个答案,我会接受你的。但这就是我现在所做的工作。

    for (Message incomingMessage : messageInitRequest.getMessageList()) {

        if (incomingMessage instanceof EmailMessage) {

            EmailMessage emailMessage = (EmailMessage) incomingMessage;

            System.out.println("Type: Email");
            System.out.println(emailMessage.getMessageBody());
            System.out.println(emailMessage.getSubject());

        } else if (incomingMessage instanceof SMSMessage) {

            SMSMessage smsMessage = (SMSMessage) incomingMessage;

            System.out.println("Type: SMS");
            System.out.println(smsMessage.getMessageBody());
        }

    }