将标头和有效负载转换为Json节点

时间:2016-12-19 12:59:41

标签: spring-integration

我正在尝试使用一些Headers键来丰富有效负载并转换为类似的json结构:

{
 "Header": { ["key" : "value", "key2": "value"]}
 "Payload": { "attribute" : "value" }
}

我的网关配置如下:

    @MessagingGateway 
public static interface MailService {
    @Gateway(requestChannel = "mail.input")
    void sendMail(String body, @Headers Map<String,String> headers);        
}

这是我的流程:

@Bean 
public IntegrationFlow errorFlow(){
    return IntegrationFlows.from(recoveryChannel())
                            .transform("payload.failedMessage")                             
                            .enrichHeaders(c -> c.header(FileHeaders.FILENAME, "emailErrors.json"))
                            .handle(this.fileOutboundAdapter())
                            .get();
}

我该如何解决这个问题?

感谢。

2 个答案:

答案 0 :(得分:2)

要将整个邮件转换为JSON,您应该执行以下操作:

.handle((p, h) -> MessageBuilder.withPayload(new GenericMessage<>(p, h)))
.transform(Transformers.toJson())

诀窍就像Transformers.toJson()不关心标题和仅转换payload一样。所以,我们必须将整个message放到payload

由于ServiceActivator.handle()的底层)返回message,如果结果为Message<?>,我们就没有选择,除非提供{{ 1}}和MessageBuilder将包含用例的所有信息。

答案 1 :(得分:0)

@SpringBootApplication
public class So41223173Application {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(So41223173Application.class, args);
        context.getBean("flow.input", MessageChannel.class)
                .send(new ErrorMessage(new MessagingException(new GenericMessage<>(new Foo()))));
        context.close();
    }

    @Bean
    public IntegrationFlow flow() {
        return f -> f.transform("payload.failedMessage")
                .enrichHeaders(c -> c.header("foo", "bar"))
                .transform(toMap(), "transform")
                .transform(Transformers.toJson())
                .handle(m -> System.out.println(m.getPayload()));
    }

    @Bean
    public Transformer toMap() {
        return new AbstractTransformer() {

            @Override
            protected Object doTransform(Message<?> message) throws Exception {
                Map<String, Object> map = new LinkedHashMap<>();
                Map<String, Object> headers = new LinkedHashMap<>(message.getHeaders());
                headers.remove(MessageHeaders.ID);
                headers.remove(MessageHeaders.TIMESTAMP);
                map.put("headers", headers);
                map.put("payload", message.getPayload());
                return map;
            }

        };

    }

    public static class Foo {

        String bar = "bar";

        public String getBar() {
            return this.bar;
        }

        public void setBar(String bar) {
            this.bar = bar;
        }

    }

}

结果

{"headers":{"foo":"bar"},"payload":{"bar":"bar"}}