Is there an easy way to tell if an arbitrary string is well-formed JSON in Android?

We are writing an application that communicates with Internet CMS in JSON. Unfortunately, some types of network connections, for example, through public Wi-Fi, have a web gateway that they require you to get through before you can use the network normally. This means that we are trying JSON to parse the HTML page. I would expect it to introduce an exception saying that HTML is not valid JSON, but instead it tries to parse it, run out of memory, and collapse.

I looked at Android JSON functions and cannot find a function that just tells you whether the string is JSON or not. Is there such a function? If not, do I just need to write something heuristic to catch explicitly non-JSON strings?

+4
source share
4 answers

Sort of:

Header contentType = httpResponse.getFirstHeader("Content-Type"); if (contentType.getValue().compareToIgnoreCase("application/json") != 0) { // response is not JSON response = null; } 
+1
source

The exact way to check for its properly formed JSON is to create a JSONObject based on the string returned from the HTTP response. A JSONException will occur if the provided string is not valid JSON.

I don’t know why you will run out of memory soon. Is it because the returned string is very large? If so, you can take advantage of the JSON format. Check the first character of the string. If it is { , then it is probably JSON. Otherwise, it is not JSON.

Pay attention to the word "possible . " This is because I don’t know if the server sometimes gives you another answer with { as its first character, and this is not JSON. You decide.

You should read the JSON string formatted here .

+3
source

You should check the HTTP header of the Content-Type response. If it returns HTML, it will be text/html . If it returns JSON, it will be application/json .

+2
source

Telling you whether this is JSON or not will require a complete analysis. Android packages parse vanilla JSON as an XML DOM parser - these parsers try to build a complete syntax tree in memory - thus, they are prone to

  • low productivity
  • large memory usage

I would suggest using parsing to pull, for example, GSON - there is also some kind of data binding that comes in handy if you need objects from your JSON or just cut binary files (16KB) for just parsing (I use it with my own binding data layer: https://github.com/ko5tik/jsonserializer )

+2
source

Source: https://habr.com/ru/post/1379647/


All Articles