Custom JSON output in Apache Camel xmljson
I think an AggregationStrategy
might help:
1) Fist you add the aggregationStrategy to your route:
<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) Then create the class that will get the Body of the message and transform it the way you want, and set the body to the Exchange again. OBS: Here You will need to use a xml
API to add the attributes you want to add.
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; }}
More here.
Is there anything preventing you from using an XSLT component? You can apply that to bring the input XML to a format that directly maps to your desired output JSON format and then push it to xmljson e.g. - (need some clean up to avoid some blank elements)
<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="Message"> <inputs> <xsl:for-each select="*"> <inputname><xsl:value-of select="name()" /> </inputname> <inputvalue><xsl:value-of select="." /></inputvalue> </xsl:for-each> </inputs> </xsl:template></xsl:stylesheet>
Use the Jackson library. You can programmatically change the output format. Unmarshal is only good for direct mapping and not enrichment. Essentially Unmarshal to xml, add a processor and then create your output Json format.