gpt4 book ai didi

java - 访问 JSON 多态 POJO 类

转载 作者:行者123 更新时间:2023-12-01 09:48:51 25 4
gpt4 key购买 nike

我正在拿起其他人编写的一些代码,但我很难理解如何访问子类。

父类:

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 消息映射的消息实例,但我无法弄清楚如何访问“类型”字段以及如何访问“主题”字段(如果是电子邮件)。

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

最佳答案

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

}

关于java - 访问 JSON 多态 POJO 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37750710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com