10

I receive a String which contains either xml or json contents.

If String contains json content I use jackson(java api) to Convert JSON to Java object

And if it contains xml contents I use JAXB to Convert XML content into a Java Object(Unmarshalling).

How can I check whether I receive xml or json in that string?

0

2 Answers 2

15

An XML document entity (in common parlance, an XML document) must start with "<".

A JSON text, according to ECMA-404, starts with zero or more whitespace characters followed by one of the following:

{ [ " 0-9 - true false null

So your simplest approach is just to test if(s.startsWith("<")

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

2 Comments

How does it validates if it is a valid Xml or JSon?
Comments are not intended for supplementary questions, especially not 6 years after the original answer. Ask a new question.
6

If the encoding of that string is known to you (or is ASCII or UTF), then looking at the very first char of that String should be enough.

If the String starts

For JSON you also have to strip whitespace before you look at the "first" char (if the String you receive may contain additional whitespace).

While it is legal for JSON data structures to begin with null, true, false you can avoid those situations if you already know a bit about your data structures.

So, basically you could check if the 1st char is a < and in that case treat it as XML. In other cases treat it as JSON and let jackson fire some exceptions if it is not legal JSON syntax.

2 Comments

JSON could also start with [.
Fair enough, I usually see { only, but others are allowed, I'll update the answer accordingly.

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.