Number of strings and JSONObjects in JSONArray
I am trying to parse a JSON schema and I need to get all image references from a JSONArray and store them in a java array. JSONArray looks like this:
How can I only get the number of rows in an array of images, eg. In this case, it should be 4? I know how to get the entire length of an array, but how can I only get the number of rows?
UPDATE:
I am just parsing it using the standard Android JSON parser. The length of the JSONArray can be calculated using:
JSONArray imageArray = hist.getJSONArray("image");
int len = imageArray.length();
len
in this case it will be 9.
source to share
I'm not sure if there is a better way (maybe there is), but here's one option:
As per Android docs , will getJSONObject
throw JSONException
if the specified index element is not a JSON object. So, you can try to get the element at each index using getJSONObject
. If it throws away JSONException
, then you don't know it is not a JSON object. Then you can try to get the element with getString
. Here's a rough example:
JSONArray imageArray = hist.getJSONArray("image");
int len = imageArray.length();
ArrayList<String> imageLinks = new ArrayList<String>();
for (int i = 0; i < len; i++) {
boolean isObject = false;
try {
JSONArray obj = imageArray.getJSONObject(i);
// obj is a JSON object
isObject = true;
} catch (JSONException ex) {
// ignore
}
if (!isObject ) {
// Element at index i was not a JSON object, might be a String
try {
String strVal = imageArray.getString(i);
imageLinks.add(strVal);
} catch (JSONException ex) {
// ignore
}
}
}
int numImageLinks = imageLinks.size();
source to share