1

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
  • You should share the complete script, to provide context, instead of just an expression. Why is the output format commented? What is the value of the variable? What is your expected output? Commented Feb 21, 2024 at 13:06

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.