以下是我当前 json 正文的日志。我想为这个 body 添加新的属性。 “新属性名称”:“值”
。由于该值在数据库中,因此我使用类中介来添加此属性。
[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"
}
类调解器的调解方法,
public boolean mediate(MessageContext mc) {
mc.setProperty("key", "vale retrived from db");
return true;
}
但这并不像我预期的那样有效。我找不到任何使用类中介向 json 正文添加属性的指南,请帮忙。
最佳答案
要向主体注入(inject)属性,您必须使用以下代码片段,
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 和其他库。以下博客文章对此进行了全面解释。
关于java - 使用 WSO2 类中介转换 JSON 主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30296197/