[java] JSON array get length

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();
    }

This question is related to java json

The answer is


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


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

You're Welcome, hope it help someone.


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.


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


Check you have the line:

 import org.json.JSONArray;

at the top of your source code


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.


have you tried size() ? Something like :

jar.size();

Hope it helps.