MuleSoft-Dataweave convert variable (" output application/json") to string error

66 Views Asked by At

I need to convert the variable (output "application/json") to string in mulesoft's dataweave

it works with

 jsonpayload: write(vars.originalPayload, "application/json")

but failed with

jsonpayload: vars.originalPayload as String 

error stack trace, why vars.originalPayload as String does not work?

Any ideas ?

Error Stack Trace

""org.mule.weave.v2.exception.UnsupportedTypeCoercionException: Cannot coerce Object { encoding: UTF-8, mediaType: application/json; charset=UTF-8, mimeType: application/json, raw: org.mule.weave.v2.el.SeekableCursorStream@44007183, contentLength: 4002 } to String

8| jsonpayload: vars.originalPayload as String,
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Trace:
  at anonymous::main (line: 8, column: 14)

" evaluating expression: "//%dw 2.0
//output application/java
//---
{
givenname: vars.firstname,
familyname:vars.lastname,
employeeid: vars.employeeId,
jsonpayload: vars.originalPayload as String,
//jsonpayload: write(vars.originalPayload, "application/json")
}"."
1

There are 1 best solutions below

0
aled On

That's the expected result. DataWeave can not convert an object to a string directly. You have to use the write() function which formats or prints its input to a string in the desired output format.

This is because internally objects are not represented as JSON or XML. There is no equivalency to a string. Formats are used only when parsing an input or formatting an output.

Having said that since the output of your script has other components you might want to just assign the variable as is and let DataWeave to write the complete output to the desired output format. Otherwise a string containing JSON may be double escaped in the final output. It depends on your expected output.