Reputation: 3103
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?
Upvotes: 10
Views: 16283
Reputation: 3592
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
<
you have XML structure. {
, [
or other allowed start characters you have a JSON structure.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.
Upvotes: 6
Reputation: 163468
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("<")
Upvotes: 15