Warm tip: This article is reproduced from stackoverflow.com, please click
java mule mule-esb mulesoft

How to convert java object to JSON after java:invoke in mule 4

发布于 2020-04-16 12:26:25

I am working with mule 4. I am invoking a java method and it returns a java object as payload. If a try to print the payload, I get something like com.myproject.services.DataInjectorManager$MyClass@7606ba6e. How Could I transform this to JSON? My mule flow is:

<flow name="processFile">
        <http:listener config-ref="HttpListenerConfig" path="/processFile" allowedMethods="GET">
            <http:response statusCode="200"/>
        </http:listener>
        <java:invoke doc:name="Invoke" doc:id="d56b8f5a-4dfa-4737-b6f3-b740585ab58d" instance="dataInjectorManager"
                     class="com.myproject.services.DataInjectorManager"
                     method="processFile(java.lang.String)">
            <java:args>#[{
                'arg0': attributes.queryParams.file
                }]
            </java:args>
        </java:invoke>
        <logger message="#[payload]" level="INFO" />
    </flow>

Thank you in advance

Questioner
Ramón Parejo Cuéllar
Viewed
43
afelisatti 2020-02-04 20:14

The log you are seeing today occurs because you don't have a toString implementation in your class so the default Object#toString is used. You could try adding that if it's just about logging. If you really want to log a JSON then you could do:

<logger message="#[output application/json --- payload]" level="INFO" />

If you also want to return that JSON as a responseo, then you need to use a transform component to turn your payload into a JSON before logging and responding:

<ee:transform >
    <ee:message >
        <ee:set-payload ><![CDATA[%dw 2.0
            output application/json
            ---
            payload]]>
        </ee:set-payload>
    </ee:message>
</ee:transform>

Note that you might have to build a more complex transformation depending on what exactly your Java object looks like and what you want in your JSON.