How to convert single child xml element to Json Array

java, json, wso2-esb, xml

Solution

There is another solution for this without using script mediator, you can add

<?xml-multiple?> 

processing instruction to your payload. as follows;

<users>
    <?xml-multiple?>
    <user>user1</user>
</users>

this will create json array for users.

{"users": {"user": ["user1"]}}

Hope this will helpful.

Problem

I am using WSO2 ESB and trying to convert my XML payload to Json. ``` <property name="messageType" value="application/json" scope="axis2"/> ``` The above property mediator convert my xml to json and it all works fine. The issue is with the child nodes in my XML payload. When the xml is ``` <users> <user>user1</user> <user>user2</user> </users> ``` it gets converted to ``` "users": { "user": [ "user1", "user2" ] } ``` so my rest full endpoint recieving the json payload which is expecting a list 'user' works fine. but when the xml is ``` <users> <user>user1</user> </users> ``` the converted json looks like this, ``` "users": { "user": "user1" } ``` So the restfull endpoint which is expecting a list of 'user' is not getting a list rather a string is sent and the datatype mismatch causes endpoint not found. If further tried, ``` <Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:json="http://james.newtonking.com/projects/json"> <users> <user json:Array="true">user1</user> </users> </Data> ``` This converts gives a json as, ``` { "Data": { "users": { "user": { "@Array": "true", "$": "user1" } } } } ``` What I need is, ``` { "Data": { "users": { "user": { [ "user1" ] } } } } ``` After Jay's suggestion, Thanks Jay, After your inputs, I tried something but I am stuck at some point. This is what I am trying, ``` mc.setPayloadJSON( { "someIds" : { "someIdList" : (vUIdLen &gt; 1 ? mc.getProperty("someIdList") : "["+someIdList+"]") } });</script> ``` I am checking the lenth of the child nodes and if it is greater than 1 than I am using the earlier captured value for that node which is ["abc","pqr"] and if it is less than or = 1 than i am using the single json value and constructing it within "["+someIdList+"]" but either of them are not getting appended. it is giving error as "The script engine returned an error executing the inlined js script function mediate". How do I append this properly. ``` (vUIdLen &gt; 1 ? mc.getProperty("someIdList") : "["+someIdList+"]") ``` The value of mc.getProperty("someIdList") above is ["abc","pqr"] and value of someIdList in "["+someIdList+"]" comes as abc. Please suggest.

Original source