【发布时间】:2014-04-17 21:27:34
【问题描述】:
我的后端服务使用 XML 响应,我默认返回它。
如果客户端给我一个添加参数(例如:&outout_format=json),我需要将响应转换为“outSequence”中的 JSON。
例如:
<result>
<foo>bar</foo>
<foo2>bar2</foo2>
<nested>
<node>value</node>
</nested>
</result>
应该回复为
{
"foo": "bar",
"foo2": "bar2",
"nested":{
"node":"value"
}
}
这是一个测试代理服务(我这里只是用 inSequence 来显示问题):
<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
name="JSONtest"
transports="https,http"
statistics="disable"
trace="disable"
startOnLoad="true">
<target>
<inSequence>
<property name="TEST_WAITING_FOR"
value="json"
scope="default"
type="STRING"/>
<header name="To" action="remove"/>
<property name="RESPONSE" value="true"/>
<property name="NO_ENTITY_BODY" scope="axis2" action="remove"/>
<payloadFactory media-type="xml">
<format>
<response xmlns="">
<result>success</result>
<code>123</code>
</response>
</format>
<args/>
</payloadFactory>
<switch source="get-property('TEST_WAITING_FOR')">
<case regex="json">
<property name="messageType"
value="application/json"
scope="axis2"
type="STRING"/>
</case>
<default>
<property name="messageType" value="text/xml" scope="axis2" type="STRING"/>
</default>
</switch>
<send/>
</inSequence>
</target>
<description/>
它响应:
{"response":{"result":"success","code":123}}
有没有什么办法可以去掉根节点的“响应”让它看起来像这样?
{"result":"success","code":123}
当我尝试使用 Enrich-mediator 删除节点“结果”时(例如 $body/result/* -> $body/*),它变成了具有多个根节点的无效 XML,并且 JSON 仅包含第一个一个。
我知道可以加载 JSON 消息,但后端可以返回具有不同格式和不同数量嵌套节点的 XML,因此我无法将其硬编码为 JSON。
看来我需要实现自己的 JSONMessageFromatter? (任何代码示例?)
UPD:我找到了解决方案(感谢Dakshika)
<payloadFactory media-type="json">
<format>$1</format>
<args>
<arg expression="$.response" evaluator="json"></arg>
</args>
</payloadFactory>
【问题讨论】: