xml to json conversion in wso2

冷暖自知 提交于 2019-12-10 19:17:13

问题


When I am trying to convert XML to Json using XSLT mediator in wso2 I am getting "Payload could not be written as JSON." error. Can anyone help to me resolve this.

Thanks in advance


回答1:


Why you do not use payload factory? this is a best way for converting xml to Json.

for example:

<payloadFactory media-type="json">
    <format>{ "error": "0", "message": "$1", "data": $2 }</format>
        <args>
            <arg evaluator="json" expression="$.USER.description"/>
            <arg evaluator="json" expression="$.USER"/>
        </args>
</payloadFactory>
<property name="ContentType" value="application/json" scope="axis2"/>

Or use this property for send message:

<property name="messageType" value="application/json" scope="axis2"/>

The media-type attribute specifies whether to format the message in XML or JSON. In this example i use JSON to convert this xml:

<USER>
    <description>some Notes</description>
    <others></others>
</USER>

and the ESB result:

{
    "error" : "0",
    "message" : "Some notes",
    "data"  : {
        "description" : "Some notes",
        "others" : ""
    }
}

for more information about payload factory please see this link: https://docs.wso2.com/display/ESB490/PayloadFactory+Mediator

Update:

you must use switch case or filter mediator. for example this is a switch case sample. you must complete regex:

 <switch source="//body">
        <case regex="">
           <payloadFactory media-type="json">

           </payloadFactory>
        </case>
 </switch>

or you can use filter. In this example, the Filter match your given regular expression or XPath. If this evaluation returns true, it will send the true json. If the evaluation returns false, it will return empty json.

<filter (source="[XPath|json-eval(JSONPath)]" regex="string") | xpath="[XPath|json-eval(JSONPath)]">
    <then>
        <payloadFactory media-type="json">
            <format>{josn:"body"}</format>
            <args>your args<args/>
        </payloadFactory>
    </then>
    <else>
        <payloadFactory media-type="json">
            <format>{}</format>
            <args/>
        </payloadFactory>
    </else>
</filter>

This link should help you: https://docs.wso2.com/display/ESB490/Filter+Mediator




回答2:


If you are trying to convert a soap service to rest, you can do it by specifying message type as (in a rest api):

 <property name="messageType" value="application/json" scope="axis2"/>


来源:https://stackoverflow.com/questions/33452167/xml-to-json-conversion-in-wso2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!