December 11, 2015

JSON Payload as String in Mediation

Due to the underlying synapse engine based on SOAP/XML message format, when a JSON payload is to be processed with ESB, it is being built as a XML message by default. In any case if we want to use the JSON payload as a string in our mediation, we will need to follow the below steps.

First the payload needs to be set as a string property as below :
<property name="JSONPayload" expression="json-eval($.)"/>
This property can then be used for any transformations as a string literal of the JSON.

Check out the sample below, which gets the response from the <call> mediator as a JSON, saves it to a string and then uses it in an xml payload. The final response of the API is XML.
<api xmlns="" name="JSONTestAPI" context="/json">
   <resource methods="GET">
            <endpoint key="MockBackend"></endpoint>
         <property name="JSONPayload" expression="json-eval($.)"></property>
         <log level="full">
            <property name="====JSONPayload====" expression="$ctx:JSONPayload"></property>
         <payloadFactory media-type="xml">
               <xmlPayload xmlns="">
               <arg evaluator="xml" expression="$ctx:JSONPayload"></arg>
         <property name="messageType" value="application/xml" scope="axis2"></property>

Response from mock backend is as below :
  "mock":"mock service"

JSON payload will be logged as below when invoking the API. Notice that although the JSON payload is built to XML, the property preserves the payload as a string literal.

LogMediator To:, WSAction: , SOAPAction: , MessageID: urn:uuid:08b4f213-0df0-4d18-88b7-8cf3e2d1872c, Direction: request, ====JSONPayload==== = {
   "mock":"mock service"
}, Envelope: <?xml version="1.0" encoding="utf-8"?><soapenv:Envelope xmlns:soapenv=""><soapenv:Body><jsonObject><mock>mock service</mock></jsonObject></soapenv:Body></soapenv:Envelope>

Final response from the API is as below :
      <jsonPayload>{"mock":"mock service"}</jsonPayload>

Additional Reference :

No comments:

Post a Comment