Apache Camel xmljson中的自定义JSON输出

Kmr*_*Gtm 9 xml json apache-camel xml-parsing

骆驼路线:

<camelContext xmlns="http://camel.apache.org/schema/spring">

   <dataFormats>
    <xmljson id="xmljson" />
   </dataFormats>

    <route id="route1">
        <from uri="file:C:/Users/User1/InputXML"/>
        <to uri="activemq:queue:MyThread1"/>        
    </route>

    <route id="route2">
        <from uri="activemq:queue:MyThread1"/>    
        <marshal ref="xmljson"/> 
        <bean ref="com.test.OutputProcessor"/>
    </route> 
</camelContext>
Run Code Online (Sandbox Code Playgroud)

输入XML:

<?xml version="1.0" encoding="UTF-8"?>
<Message>
  <to> Tove</to>
 <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</Message>
Run Code Online (Sandbox Code Playgroud)

实际产量:

{"to":" Tove","from":"Jani","heading":"Reminder","body":"Don't forget me this weekend!"}
Run Code Online (Sandbox Code Playgroud)

我想自定义此输出.我想为转换后的json添加一些mote属性.例如,我希望输出json为

  {
    "inputs":[  
                { 
            "inputname":"to",
            "inputValue":"Tove"
            },
            { 
            "inputname":"from",
            "inputValue":"jani"
            },
            { 
            "inputname":"heading",
            "inputValue":"Reminder"
            },
            { 
            "inputname":"body",
            "inputValue":"Don't forget me this weekend!"
            }
        ]
    }
Run Code Online (Sandbox Code Playgroud)

如何实现这一目标?

edu*_*nti 1

我认为AggregationStrategy可能有帮助:

1)首先将aggregationStrategy添加到您的路由中:

<camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
  <route>
    <from uri="direct:start"/>
    <enrich strategyRef="aggregationStrategy">
      <constant>direct:resource</constant>
    <to uri="direct:result"/>
  </route>
  <route>
    <from uri="direct:resource"/>
    ...
  </route>
</camelContext>

<bean id="aggregationStrategy" class="com.ExampleAggregationStrategy" />
Run Code Online (Sandbox Code Playgroud)

2) 然后创建一个类,该类将获取消息的正文并将其转换为您想要的方式,然后再次将正文设置为 Exchange。 OBS:这里您需要使用xmlAPI​​来添加您想要添加的属性。

public class ExampleAggregationStrategy implements AggregationStrategy {

    public Exchange aggregate(Exchange original, Exchange resource) {
        Object originalBody = original.getIn().getBody();
        Object resourceResponse = resource.getIn().getBody();
        Object mergeResult = ... // combine original body and resource response
        if (original.getPattern().isOutCapable()) {
            original.getOut().setBody(mergeResult);
        } else {
            original.getIn().setBody(mergeResult);
        }
        return original;
    }

}
Run Code Online (Sandbox Code Playgroud)

更多这里