Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

android

We're writing an app that communicates with an internet-based CMS in JSON. Unfortunately, some types of network connection e.g. through public Wifi have a web gateway that they require you to go through before you can use the net normally. This means we are trying to JSON parse an HTML webpage. I would expect it to throw an exception stating that the HTML isn't well-formed JSON but instead it tries to parse it, runs out of memory and collapses.

I have looked through the Android JSON functions and can't find a function that simply tells you if a string is JSON or not. Is there such a function? If not, am I simply going to have to write something heuristic to trap obviously non-JSON strings?

like image 678
Andrew Wyld Avatar asked Feb 22 '23 12:02

Andrew Wyld


2 Answers

The exact way to check for its well-formed JSON is to create a JSONObject based on the string returned from HTTP Response. JSONException will occurs if the resulted string is not a well-formed JSON.

I don't know why you're running out of memory too soon. Is it because the returned string is very large? If so, you can take the advantages of the JSON format. Check the first character of the string. If it's { then it's probably JSON. Otherwise, it's not a JSON.

Please note the word "probably". It's because I don't know whether the server sometimes gives you another response with { as its first character and it's not a JSON. You decide.

You should read a JSON string formatted here.

like image 136
Kristiono Setyadi Avatar answered May 02 '23 03:05

Kristiono Setyadi


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

like image 26
Brigham Avatar answered May 02 '23 02:05

Brigham