我正在关注此guide,以阅读来自Google Pub / Sub中某个主题的电子邮件通知。应用程序启动后,我会看到如下消息到达控制台:
Message arrived! Payload: {"emailAddress":"xxxxx@gmail.com","historyId":712315}
如何将有效负载转换为对象,以便可以检索emailAddress和historyId?
服务激活器如下:
@Bean
@ServiceActivator(inputChannel = "pubsubInputChannel")
public MessageHandler messageReceiver() {
return message -> {
LOGGER.info("Message arrived! Payload: " + message.getPayload());
AckReplyConsumer consumer =
(AckReplyConsumer) message.getHeaders().get(GcpPubSubHeaders.ACKNOWLEDGEMENT);
consumer.ack();
};
}
我要将有效负载转换为的POJO对象是:
public class MessageNotification {
private String emailAddress;
private BigInteger historyId;
public String getEmailAddress() {
return emailAddress;
}
public BigInteger getHistoryId() {
return historyId;
}
public void setHistoryId(BigInteger historyId) {
this.historyId = historyId;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
}
答案 0 :(得分:1)
看起来payload
是JSON,因此您需要先使用Spring Integration Reference Manual并使用JsonToObjectTransformer
,然后再使用该@ServiceActivator
:
@Bean
@Transformer(inputChannel = "pubsubInputChannel", outputChannel = "handleChannel")
public JsonToObjectTransformer jsonToObjectTransformer() {
return new JsonToObjectTransformer(MessageNotification.class);
}
@Bean
@ServiceActivator(inputChannel = "handleChannel")
public MessageHandler messageReceiver() {
...
答案 1 :(得分:-1)
You can extract String message first: String jsonString =message.getPayload.toString();
Now you can convert this json string to:
ObjectMapper objectMapper = new ObjectMapper();
MessageNotification messageNotification = objectMapper.readValue(jsonString , MessageNotification.class);