How to write custom mediator in Wso2 ei to convert json list of list payload into single list

Viewed 195

I try to convert my wso2 aggregated list of list response into single list. But script mediator doesnt work. so i try with custom mediator. That mediator function is,

public void process(MessageContext mc) {
        String s = (String)mc.getProperty("data")).toString();
        ArrayList<String> list = new ArrayList<String>();     
        JSONArray jsonArray = new JSONArray(s); 
        if (jsonArray != null) { 
            int len = jsonArray.length();
            int len2 = 0;
            JSONArray j2;
            for (int i=0;i<len;i++){ 
                j2 = new JSONArray(jsonArray.get(i));
                len2 = j2.length();
                for (int j=0;j<len2;j++){ 
                    list.add(j2.get(j).toString());
                }
            } 
        } 
        mc.setProperty("data", list.toString());
    }

but when i use it there is an error. Are there any possible way to do this. without using custom mediator. Basically my "data" parameter value something like this,

[
[{'a1':12,'b1':'sd'},
        {'a1':12,'b1':'sd'}],
[{'a1':12,'b1':'sd'},
        {'a1':12,'b1':'sd'}],
[{'a1':12,'b1':'sd'},
        {'a1':12,'b1':'sd'}]
]

what i need after the mediation is,

[
{'a1':12,'b1':'sd'},
        {'a1':12,'b1':'sd'},
{'a1':12,'b1':'sd'},
        {'a1':12,'b1':'sd'},
{'a1':12,'b1':'sd'},
        {'a1':12,'b1':'sd'}]

Please help me.

1 Answers

Can you confirm that you are receiving the data entry as a JSON accepted format (with double quotes enclosure and not single quote)?

For example

[
    [{"a1": 12,"b1": "sd"},{"a1": 12,"b1": "sd"}],
    [{"a1": 12,"b1": "sd"},{"a1": 12,"b1": "sd"}],
    [{"a1": 12,"b1": "sd"},{"a1": 12,"b1": "sd"}]
]

If yes, then modify the mentioned class mediator logic as following and try out the scenario

import java.util.ArrayList;

import org.apache.synapse.MessageContext;
import org.apache.synapse.commons.json.JsonUtil;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.mediators.AbstractMediator;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

public boolean mediate(MessageContext mc) {
    ...

    String dataBody = (String) mc.getProperty("data");

    ArrayList<JSONObject> listdata = new ArrayList<JSONObject>();
    JSONArray jArray = new JSONArray(dataBody);

    if (jArray != null) {
        int len = jArray.length();
        int len2 = 0;
        JSONArray jArray2;
        for (int i = 0; i < len; i++) {
            jArray2 = jArray.getJSONArray(i);
            len2 = jArray2.length();
            for (int j = 0; j < len2; j++) {
                listdata.add(jArray2.getJSONObject(j));
            }
        }
    }

    log.info("JSON Array: " + listdata.toString());
    JSONArray mod = new JSONArray(listdata);

    ...
}
Related