Reputation: 1224
I'm trying to take the information from the JSON returned by Google Places.
jsonObj = new JSONObject(data);
JSONArray results = jsonObj.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
System.out.println(result.getString("name"));
if (result.getJSONArray("reviews") != null){
JSONArray reviewsArray = result.getJSONArray("reviews");
JSONObject reviews = reviewsArray.getJSONObject(0);
if (reviews != null){
String review = reviews.getString("text");
Log.d("tag", "review: " + review);
}
}
}
My question is, how can I make sure the either "name" or "reviews" are available to parse? that if (result.getJSONArray("reviews") != null)
still fails because getJSONArray is empty.
Upvotes: 0
Views: 1831
Reputation: 8870
Since your json is initially in the form of a JSONObject, you could use it's isNull(String name)
helper method to check if a mapping exists and isn't null.
From the documentation:
isNull(String name) Returns true if this object has no mapping for name or if it has a mapping whose value is NULL.
For example:
try {
jsonObj = new JSONObject(data);
if(!jsonObj.isNull("results")){
JSONArray results = jsonObj.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
if(!result.isNull("name"){
System.out.println(result.getString("name"));
}
if (result.getJSONArray("reviews") != null){
JSONArray reviewsArray = result.getJSONArray("reviews");
JSONObject reviews = reviewsArray.getJSONObject(0);
if (reviews != null){
String review = reviews.getString("text");
Log.d("tag", "review: " + review);
}
}
}
}
} catch(JSONException e){
//Something went wrong
}
Upvotes: 0
Reputation: 24857
You can do this by using the opt commands instead of the get commands. Change the get json array to the following:
(result.optJSONArray("reviews") != null)
Check out the JSONObject documentation for a complete list. You can also use the JSONObject has(String name) command to check if it exists before actually getting it.
Upvotes: 2