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?
Very simple: Valid JSON starts always with '{' or '[' Valid XML starts always with '<'
In order to check the validity of a string whether it is a JSON string or not, We're using the JSON. parse()method with few variations. This method parses a JSON string, constructs the JavaScript value or object specified by the string.
The common approach for checking if a String is a valid JSON is exception handling. Consequently, we delegate JSON parsing and handle the specific type of error in case of incorrect value or assume that value is correct if no exception occurred.
All json strings start with '{' or '[' and end with the corresponding '}' or ']', so just check for that.
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("<")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With