gpt4 book ai didi

json - Apache Camel xmljson 中的自定义 JSON 输出

转载 作者:数据小太阳 更新时间:2023-10-29 01:43:44 24 4
gpt4 key购买 nike

Camel 路线:

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

输入 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>

实际输出:

{"to":" Tove","from":"Jani","heading":"Reminder","body":"Don't forget me this weekend!"}

我想自定义这个输出。我想向转换后的 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!"
}
]
}

如何实现?

最佳答案

我认为 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" />

2) 然后创建将获取消息正文 的类并按照您想要的方式对其进行转换,然后再次将正文设置为Exchange。OBS:在这里您需要使用 xml API 来添加您要添加​​的属性。

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

}

更多here .

关于json - Apache Camel xmljson 中的自定义 JSON 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31023852/

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