2
votes

I have a String input to my API. It can be either XML or JSON and I need to use the Read function on it to parse it into JSON. What is the best way in MuleSoft 4 or Dataweave 2 to determine what format the String is in?

Maybe I could write a function isXML(String inputString) or isJSON(String inputString).

As of now, I have something inelegant. I'm trying to parse the input as XML and catching any parsing exceptions. Inside the catch, I'll try to parse it as JSON. I guess it's not a horrible solution.

1

1 Answers

5
votes

Try this:

%dw 2.0
output application/dw
var xml = "<test>XML</test>"
var json = '{"test":1, "test2": 2}'
var test = xml
---
// Try to read it as a JSON
dw::Runtime::try(() -> read(test,"application/json")) 
// Now try to read it as an XML
dw::Runtime::orElseTry(() -> read(test,"application/xml"))
// You have data that are neither of XML or JSON
dw::Runtime::orElse("Not XML or JSON")