Reputation: 7080
i'm working with JSON objects . it gives result like this
{
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 19.0759817,
"lng" : 80.27071789999999
},
"southwest" : {
"lat" : 12.5100381,
"lng" : 72.8772599
}
},
"copyrights" : "Map data ©2015 Google",
"legs" : [
{
"distance" : {
"text" : "1,334 km",
"value" : 1333618
},
"duration" : {
"text" : "17 hours 43 mins",
"value" : 63763
},
"end_address" : "Mumbai, Maharashtra, India",
"end_location" : {
"lat" : 19.0759817,
"lng" : 72.8776544
},
"start_address" : "Chennai, Tamil Nadu, India",
"start_location" : {
"lat" : 13.0826782,
"lng" : 80.27071789999999
},
so i'm retrieving following arrays routes
->legs->
distance` . with following code
JSONArray one = reader.getJSONArray("routes");
for ( i = 0; i < one.length(); i++) {
two = one.getJSONObject(i);
three = two.getJSONArray("legs");
for ( j = 0; j < three.length(); j++) {
four = three.getJSONObject(j);
bounds = four.getJSONObject("distance");
distance[i]=bounds.getString("text");
it works fine. sometimes my JSON result is like this when wrong input.
{
"routes" : [],
"status" : "NOT_FOUND"
}
so when i'm search legs in this empty JSON object so my android app hangs and terminated automatically. so i should check whether legs
array present in my JSON object or not .
if present i will work with my code. otherwise i will just show warning messages to users.
Upvotes: 0
Views: 1964
Reputation: 1762
JSONObject class has a method named "has"
http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)
Returns true if this object has a mapping for name. The mapping may be NULL.
example
if (jsonObject.has("yourkey"))
{
// it will return true;
}
else
{
//it will return false;
}
Upvotes: 1
Reputation: 2326
you can check the length or routes arary and do your stuff if it has data in it:
JSONArray one = reader.getJSONArray("routes");
if(one.size()>0)
{
for ( i = 0; i < one.length(); i++) {
two = one.getJSONObject(i);
three = two.getJSONArray("legs");
for ( j = 0; j < three.length(); j++) {
four = three.getJSONObject(j);
bounds = four.getJSONObject("distance");
distance[i]=bounds.getString("text");
}}
else
{//handle empty json array here
}
Upvotes: 2