Following is the log of my current json body. And I want to add new property to this body. "NewPropertyName": "value"
. Since the value is in a database I am using a class mediator to add this property.
[2015-05-18 05:47:08,730] INFO - LogMediator To: /a/create-project, MessageID: urn:uuid:b7b6efa6-5fff-49be-a94a-320cee1d4406, Direction: request, _______BODY_______ =
{
"token": "abc123",
"usertype":"ext",
"request": "create"
}
Class mediator's mediate method,
public boolean mediate(MessageContext mc) {
mc.setProperty("key", "vale retrived from db");
return true;
}
but this doesn't work as I expected. I couldn't find any guide to add property to json body using class mediator, please help.
To inject a property to the body you have to use following code snippet,
JsonUtil.newJsonPayload(
((Axis2MessageContext) context).getAxis2MessageContext(),
transformedJson, true, true);
inside a class mediator. Following is an example of mediate method.
/**
* 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;
}
You will need json and other libraries for this. This is fully explained in following blog post.
json-support-for-wso2-esb-class-mediator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With