24

I can't get the array length of the JSON array. when I using length(); method it is not working, it show as red underline in Netbeans

this is the source code

 try {

        JSONObject myjson = JSONObject.fromObject(practiceInfoByUsername);

        //JSONArray nameArray = myjson.names();
        final JSONArray jar = myjson.getJSONArray("_types");
        for(int i=0; i<jar.length(); i++)
        {
            String p = jar.getString(i);
            Log.i("p",p);


        }

    } catch (JSONException e) {
            e.printStackTrace();
    }
1
  • Does it compile? May be issue with netbean's highlighting. Commented Feb 13, 2012 at 21:22

7 Answers 7

51

Note: if you're using(importing) org.json.simple.JSONArray, you have to use JSONArray.size() to get the data you want. But use JSONArray.length() if you're using org.json.JSONArray.

Sign up to request clarification or add additional context in comments.

Comments

7

have you tried size() ? Something like :

jar.size();

Hope it helps.

Comments

4

I came here and looking how to get the number of elements inside a JSONArray. From your question i used length() like that:

JSONArray jar = myjson.getJSONArray("_types");
System.out.println(jar.length());

and it worked as expected. On the other hand jar.size();(as proposed in the other answer) is not working for me.

So for future users searching (like me) how to get the size of a JSONArray, length() works just fine.

Comments

2

The below snippet works fine for me(I used the size())

String itemId;
            for (int i = 0; i < itemList.size(); i++) {
            JSONObject itemObj = (JSONObject)itemList.get(i);
            itemId=(String) itemObj.get("ItemId");
            System.out.println(itemId);
            }

If it is wrong to use use size() kindly advise

Comments

0

Check you have the line:

 import org.json.JSONArray;

at the top of your source code

Comments

0

The JSONArray.length() returns the number of elements in the JSONObject contained in the Array. Not the size of the array itself.

Comments

0

At my Version the function to get the lenght or size was Count()

You're Welcome, hope it help someone.

Comments

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.