3

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.

1
  • 2
    What JSON parser are you using? Can you clarify what you mean when you say I know how to get the full length of array but how can I only get the number of strings? Commented Jun 25, 2015 at 23:36

1 Answer 1

3

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();
Sign up to request clarification or add additional context in comments.

1 Comment

You interpreted it wrong, there is no subArray. There is only 1 array image which contains few strings and few JSONObjects. I can get total number of elements in a JSONArray using imageArray.length(); but if I had to get only the number of strings then how can I get that number?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.