Peter
Peter

Reputation: 1894

org.json.JSONArray to payload in Mulesoft

I'm using a java class to transform a datastructure in my mule application. At the end of my flow I would like to access the result and return it as application/json.
When debugging I get these values for payload:
Mule Debug
The Transform component recognizes a payload of type org.json.JSONArray. Under it a var myArrayList, which I didn't assign that holds all values.
The getNodes() method in java looks like this:

public JSONArray getNodes() {
    JSONArray arr = new JSONArray();
    for(Node node : nodes) {
        arr.put(node.getJSON());
    }
    return arr;
}

Where the return value is correct.
I tried setting the MIME type of the Invoke component to application/json or text/plain, both of which resulted in an error.
I tried returning the payload as output application/json---payload which resulted in an array of empty objects the size of my return value.
When looking at the watch I get the list by accessing payload.myArrayList, but can't seem to get the value in a transform component.
The flow looks like this.
Flow
How I return json from JSONArray in mulesoft?

Edit: Solution:

public Node[] getNodes() {
    assignParentIds();
    assignNextIds();
    assignChildIds();
        
    Node[] nodeArr = new Node[nodes.size()];
    for(int i = 0; i < nodes.size(); i++) {
        nodeArr[i] = nodes.get(i);
    }
    return nodeArr;
}

Node Metadata

%dw 2.0
output application/json
---
{
    hierarchieSet: payload map ( item , index ) -> {
        zshop: item.zshop,
        nodeid: item.nodeid,
        nodename: item.nodename,
        tlevel: item.tlevel,
        parentid: item.parentid,
        childid: item.childid,
        nextid: item.nextid
    }
}

Upvotes: 1

Views: 718

Answers (1)

aled
aled

Reputation: 25699

I suspect DataWeave understand org.json.JSONArray as an iterable because it implements Iterable<Object>, however it doesn't understand particularly JSON nodes. For DataWeave application/json is a string or stream that contains a 'textual' representation of JSON. A third party library that represents JSON using Java objects as its implementation is just not going to be understood as JSON and it is not the correct usage of the application/json MIME type.

You should serialize the resulting JSON array back to a text document to be used as the input of the Transform processor.

Alternatively you could convert the JSON structures to plain Java objects (POJOs) an use as application/java. That should be more efficient because avoids converting to JSON and parsing it again.

Upvotes: 1

Related Questions