简体   繁体   中英

How to convert single child xml element to Json Array

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.

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.

Use script mediator to build payload. please refer following links.

[1]. https://docs.wso2.com/display/ESB480/Script+Mediator .

[2]. https://docs.wso2.com/display/ESB480/JSON+Support

If anybody looking for converting the XML to Json, the below method can be used. It encloses all JSONObject inside a JSONArray.

public JSONObject getJSONFromXML(String xml) {
    JSONObject jsonObject = null;
    try {
        jsonObject = XML.toJSONObject(xml);
        convertJsonObjectToArray(jsonObject);
    } catch (JSONException e) {
        System.out.println("Error in parsing JSON From xml: " + e);
    }
    return jsonObject;
}

private void convertJsonObjectToArray(JSONObject jsonObject) throws JSONException {
    for (Object key : jsonObject.keySet()) {
        Object val = jsonObject.get(key.toString());
        if (val instanceof JSONObject) {
            convertJsonObjectToArray((JSONObject) val);
            JSONArray jsonArray = new JSONArray();
            jsonArray.put(val);
            jsonObject.put(key.toString(), jsonArray);
        } else if (val instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) val;
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject obj = (JSONObject) jsonArray.get(i);
                convertJsonObjectToArray(obj);
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM