JSON Support for WSO2 ESB Class Mediator


In WSO2 documentation you can find how the following mediators can be used with json payloads.

  • Log Mediator
  • Property Mediator
  • PayloadFactory Mediator
  • Switch Mediator
  • Filter Mediator

But there’s no any clue about how the class mediator can be used with json payloads. Following is the way you can do manipulation to json payload using class mediator.

In this post I just add a new tag to existing json payload

package com.wso2.test;

import org.apache.synapse.MessageContext;
import org.apache.synapse.commons.json.JsonUtil;
import org.json.JSONObject;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.mediators.AbstractMediator;

/**
* Class mediator for JSON transformation.
*
* @author isuru
*
*/
public class JSONClassMediator extends AbstractMediator {

/**
* Holds the name.
*/
private String nameParam;

/**
* Mediate overridden method to set the token property.
*/
@Override
public boolean mediate(MessageContext context) {

try {

// Getting the json payload to string
String jsonPayloadToString = JsonUtil
.jsonPayloadToString(((Axis2MessageContext) context)
.getAxis2MessageContext());
// Make a json object
JSONObject jsonBody = new JSONObject(jsonPayloadToString);

// Adding the name:nameParam.
jsonBody.put("name", getNameParam());

String transformedJson = jsonBody.toString();

// Setting the new json payload.
JsonUtil.newJsonPayload(
((Axis2MessageContext) context).getAxis2MessageContext(),
transformedJson, true, true);

System.out.println("Transformed JSON body:\n" + transformedJson);

} catch (Exception e) {
System.err.println("Error occurred: " + e);
return false;
}

return true;
}

/**
* @return the nameParam
*/
public final String getNameParam() {
return nameParam;
}

/**
* @param nameParam
* the nameParam to set
*/
public final void setNameParam(String nameParam) {
this.nameParam = nameParam;
}
}

And following maven dependency includes the org.json.JSONObject class

<dependency>
 <groupId>org.json</groupId>
 <artifactId>json</artifactId>
 <version>20141113</version>
 </dependency>

Following maven dependency includes the org.apache.synapse.commons.json.JsonUtil class

<dependency>
 <groupId>org.apache.synapse</groupId>
 <artifactId>synapse-commons</artifactId>
 <version>2.1.2-wso2v4</version>
 </dependency>

and in order to build this you must and the following repository to the pom.xml

<repository>
 <releases>
 <enabled>true</enabled>
 <updatePolicy>daily</updatePolicy>
 <checksumPolicy>ignore</checksumPolicy>
 </releases>
 <id>wso2-nexus</id>
 <url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
 </repository>