Hasala
Hasala

Reputation: 126

How to handle empty JSONObject in Processing?

Hi I am using loadJSONObject function in Processing IDE to receive a JSON Object from a URL. Following is my code:

      JSONObject jsonUserLocations = loadJSONObject("http://smrt.utd.sg/eLocation/getLocs.php?userId="+usrID+"&sTime="+strtTime+"&eTime="+endTym);

This code works when the php returns some data (for some users). The problem occurs when it doesn't return any data. (php doesn't return any data when there is no data, browser shows a blank page. this means user has no location data)

At this instance, the Processing IDE gives me an error saying;

a jsonobject text must begin with {

My question is how can I handle empty JSON Object in this type of situation? I need to skip if this is empty and request data for next user. Your help is much appreciated. Thanks, Hasala

Edit:

This is sample json object I receive when there is data.

{"locations":[{"latitude":"1.3809274","longitude":"103.7654596","startTime":"1421918587868","duration":"0","accuracy":"30"},{"latitude":"1.3805307","longitude":"103.7661015","startTime":"1421941711737","duration":"0","accuracy":"45"},{"latitude":"1.3805304","longitude":"103.7660959","startTime":"1421942011727","duration":"0","accuracy":"45"},{"latitude":"1.3799822","longitude":"103.7658037","startTime":"1421942311835","duration":"0","accuracy":"82.5"}],"success":1}

Upvotes: 0

Views: 205

Answers (1)

Kevin Workman
Kevin Workman

Reputation: 42174

You have two options:

You could read the String form the URL first, and if it's blank, don't bother with the parsing.

Or you could just catch the exception that Processing throws:

try{
   JSONObject jsonUserLocations = loadJSONObject("http://smrt.utd.sg/eLocation/getLocs.php?userId="+usrID+"&sTime="+strtTime+"&eTime="+endTym);
}
catch(JSONException e){
   e.printStackTrace();
   //json was blank, do something else
}

Upvotes: 2

Related Questions