newbie
newbie

Reputation: 600

Count number of Strings and JSONObjects in JSONArray

I am trying to parse a JSON schema and I need to get all the image links from the JSONArray and store it in a java array. The JSONArray looks like this:

enter image description here

How can I get only the number of strings in the image array for e.g. In this case it should be 4? I know how to get the full length of array but how can I only get the number of strings?

UPDATE:

I am simply parsing it using the standard JSON parser for android. The length of JSONArray can be calculated using:

JSONArray imageArray = hist.getJSONArray("image");
int len = imageArray.length();

len will be equal to 9 in this case.

Upvotes: 3

Views: 9642

Answers (1)

mittmemo
mittmemo

Reputation: 2090

I'm not sure if there's a better way (there probably is), but here's one option:

According to the Android docs, getJSONObject will throw a JSONException if the element at the specified index is not a JSON object. So, you can try to get the element at each index using getJSONObject. If it throws a JSONException, then you know it's not a JSON object. You can then try and get the element using getString. Here's a crude 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();

Upvotes: 3

Related Questions