使用 WSO2 class 调解器转换 JSON body

Transforming JSON body using WSO2 class mediator

以下是我目前jsonbody的日志。我想向这个 body 添加新的 属性。 "NewPropertyName": "value"。由于该值在数据库中,因此我使用 class 中介来添加此 属性.

[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调解员的调解方式,

public boolean mediate(MessageContext mc) {
        mc.setProperty("key", "vale retrived from db");
        return true;
}

但这并不像我预期的那样有效。我找不到任何使用 class 调解器将 属性 添加到 json body 的指南,请帮忙。

mc.setProperty 用于创建新的 属性,就像您使用 属性 中介一样。

如果您想在消息中添加新元素,在 java 中,您可以将其视为 XML 消息(例如,获取第一个元素:
OMElement element = (OMElement) context.getEnvelope().getBody().getFirstOMChild(); )

使用 java 脚本添加新元素的示例:

<script language="js"><![CDATA[
    var payloadXML = mc.getPayloadXML();
    payloadXML.appendChild(new XML(<NewPropertyName>value</NewPropertyName>));
    mc.setPayloadXML(payloadXML);
]]></script>

使用 <log level="full"> 在 XML 中记录消息,您会得到:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <jsonObject>
      <token>abc123</token>
      <usertype>ext</usertype>
      <request>create</request>
      <NewPropertyName>value</NewPropertyName>
    </jsonObject>
  </soapenv:Body>
</soapenv:Envelope>

将消息记录在 JSON 中

<log>
  <property name="JSON-Payload" expression="json-eval($.)"/>
</log> 

你会得到: JSON-有效负载={"token":"abc123","usertype":"ext","request":"create","NewPropertyName":"value"}

要将 属性 注入正文,您必须使用以下代码片段,

JsonUtil.newJsonPayload(
            ((Axis2MessageContext) context).getAxis2MessageContext(),
            transformedJson, true, true);

在 class 调解员内部。以下是中介方法的示例。

/**
 * 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;
}

为此您需要 json 和其他库。这在以下博客 post.

中得到了充分解释

json-support-for-wso2-esb-class-mediator