Search code examples
javajsonspringjacksonpojo

Access JSON Polymorphic POJO Class


I'm picking up some code that someone else wrote and I'm having a hard time understanding how to access the child class.

Parent Class:

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;
   }
}

Child Class:

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;
   }
}

Child Class:

package blah.blah.blah;

public class SMSMessage extends Message {
}

I have an instance of Message that was mapped from a JSON message but I cannot figure out how to access the 'Type' field and how to access the 'Subject' field (if it's an email).

JSON:

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

What I've tried:

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

Solution

  • Thanks @cricket_007 and @zapl for the answer in the comments. Feel free to write this answer and I'll accept yours. But here is what I have now that is working.

        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());
            }
    
        }