Sunday, March 13, 2016

[ESB]Transform Message Content using Payload Factory Mediator in WSO2 ESB

Payload Factory Mediator 

 

 

This mediator can be used to transform/replace the content of a message in to desired format(XML/JSON/text).
Eg: Let's consider about a client server system.
Server sends the JSON format responses , but in the client side understand the XML format responses only. In this case we need to transform the JSON format responses in to XML format responses. We can do this using Payload Factory Mediator. 

How to transform a message JSON to XML format


Sample response in JSON format .


{
    "login": "peff",
    "id": 45925,
    "avatar_url":
"https://avatars.githubusercontent.com/u/45925?v=3",
    "gravatar_id": "",
    "url":
"https://api.github.com/users/peff",
    "html_url":
"https://github.com/peff",
    "followers_url":
"https://api.github.com/users/peff/followers",
    "following_url":
"https://api.github.com/users/peff/following{/other_user}",
    "gists_url":
"https://api.github.com/users/peff/gists{/gist_id}",
    "starred_url":
"https://api.github.com/users/peff/starred{/owner}{/repo}",
    "subscriptions_url":
"https://api.github.com/users/peff/subscriptions",
    "organizations_url":
"https://api.github.com/users/peff/orgs",
    "repos_url":
"https://api.github.com/users/peff/repos",
    "events_url":
"https://api.github.com/users/peff/events{/privacy}",
    "received_events_url":
"https://api.github.com/users/peff/received_events",
    "type": "User",
    "site_admin": true,
    "contributions": 2065
  }
Let's transform the above response in to following XML format .

<contributor>
<name>peff</name>
<contribution>2065</contribution>
</contributor>

You can do this by adding the following payloadFactory mediator .



<payloadFactory media-type="xml">
<format>
<contributor xmlns="">
<name>$1</name>
<contribution>$2</contribution>
</contributor>
</format>
<args>
<arg expression="//jsonElement/login/text()" evaluator="xml"/>
<arg expression="//jsonElement/contributions/text()" evaluator="xml"/>
</args>
</payloadFactory>

You can create a payloadFactory through the UI.

To do this first you need to add the payloadFactory mediator inside the insequence of the proxy service as shown below.



 

Then you can create the payload format and you can add the arguments using Xpath expressions as shown in below figure.


 

No comments:

Post a Comment