Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string either contains xml or json data

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?

like image 364
Shahid Ghafoor Avatar asked Dec 19 '13 08:12

Shahid Ghafoor


People also ask

How do I check if a string is XML or JSON?

Very simple: Valid JSON starts always with '{' or '[' Valid XML starts always with '<'

How do I check if a string is valid in JSON?

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.

How do you check if a string is a JSON string in Java?

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.

How do you check if it is JSON?

All json strings start with '{' or '[' and end with the corresponding '}' or ']', so just check for that.


2 Answers

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("<")

like image 132
Michael Kay Avatar answered Oct 22 '22 03:10

Michael Kay


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

  • with < you have XML structure.
  • with {, [ 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.

like image 43
Matthias Avatar answered Oct 22 '22 02:10

Matthias