Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom JSON output in Apache Camel xmljson

Camel Route :

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

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

Actual output :

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

I want to customize this output. i want to add some mote attributes to the converted json. For Example i want the output json as

  {
    "inputs":[  
                { 
            "inputname":"to",
            "inputValue":"Tove"
            },
            { 
            "inputname":"from",
            "inputValue":"jani"
            },
            { 
            "inputname":"heading",
            "inputValue":"Reminder"
            },
            { 
            "inputname":"body",
            "inputValue":"Don't forget me this weekend!"
            }
        ]
    }

How this can be achieved ?

like image 495
DKingKumar Avatar asked Jun 24 '15 10:06

DKingKumar


1 Answers

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.

like image 128
edubriguenti Avatar answered Oct 30 '22 13:10

edubriguenti